美文网首页
AVFoundation编程指南(二)

AVFoundation编程指南(二)

作者: 洱舟 | 来源:发表于2020-05-19 10:46 被阅读0次

    官方文档:AVFoundation Programming Guide

    使用Asset

    asset可以来自文件,也可以来自用户iPod库或照片库中的媒体。创建asset对象时,可能要立即检索该项目的所有信息都不是立即可用的。拥有电影资产后,您可以从其中提取静止图像,将其转码为另一种格式或修剪内容。

    创建Asset对象

    要创建asset来表示您可以使用URL识别的任何资源,请使用AVURLAsset。最简单的情况是从文件创建asset:

    NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;
    AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
    
    初始化资产的选项

    AVURLAsset初始化方法需要作为自己的第二个参数的选项字典。词典中使用的唯一键是AVURLAssetPreferPreciseDurationAndTimingKey。相应的值是一个布尔值(包含在一个NSValue对象中),它指示是否应准备资产以指示精确的持续时间并按时间提供精确的随机访问。

    获取资产的确切期限可能需要大量的处理开销。使用近似持续时间通常是较便宜的操作,并且足以播放。从而:

    1. 如果仅打算播放资产,请通过nil而不是字典,或通过包含AVURLAssetPreferPreciseDurationAndTimingKey键和对应值NO(包含在NSValue对象中)的字典。
    2. 如果要将资产添加到合成(AVMutableComposition),通常需要精确的随机访问。通过一个包含AVURLAssetPreferPreciseDurationAndTimingKey键和对应值YES(包含在NSValue对象中的调用的NSNumber继承自的字典)的字典NSValue
    NSURL * url = <#标识视听资产(如电影文件)的URL#>;
    NSDictionary * options = @ {AVURLAssetPreferPreciseDurationAndTimingKey:@YES};
    AVURLAsset * anAssetToUseInAComposition = [[[AVURLAsset alloc] initWithURL:url options:options];
    

    访问用户的资产

    要访问由iPod库或“照片”应用程序管理的资产,您需要获取所需资产的URL。

    要访问iPod库,您可以创建一个MPMediaQuery实例来查找所需的项目,然后使用来获取其URL MPMediaItemPropertyAssetURL
    有关媒体库的更多信息,请参见《多媒体编程指南》

    //获取用户相册中所有图片
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 获得所有的自定义相簿
        PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
            
        // 遍历所有的自定义相簿(不包含最近相簿),所以还需要获取最近相簿照片
        for (PHAssetCollection *assetCollection in assetCollections) {
            NSLog(@"assetCollections = %@",assetCollection.localizedTitle);
            [self enumerateAssetsInAssetCollection:assetCollection original:YES];
        }
            
        // 最近相簿照片
        PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
            // 遍历最近相簿照片
            [self enumerateAssetsInAssetCollection:cameraRoll original:YES];
    });
    
    - (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection original:(BOOL)original
    {
        NSLog(@"相簿名:%@", assetCollection.localizedTitle);
        
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeFast;
        // 同步获得图片, 只会返回1张图片
        options.synchronous = YES;
        
        // 获得某个相簿中的所有PHAsset对象
        PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
        
        for (PHAsset *asset in assets) {
            // 是否要原图
            CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;
            
            // 从asset中获得图片
            __weak typeof(self) weakSelf = self;
            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                NSLog(@"相册照片 = %@", result);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //具体操作放在主线程
                });
            }];
        }
    }
    

    准备Asset以供使用

    初始化asset(或track)并不一定意味着您可能要检索该项目的所有信息都立即可用。甚至可能需要一段时间来计算项目的持续时间(例如,MP3文件可能不包含摘要信息)。而不是在计算值时阻塞当前线程,您应该使用AVAsynchronousKeyValueLoading 协议来询问值并稍后通过使用block定义的完成处理程序获得答案。(AVAsset并AVAssetTrack符合AVAsynchronousKeyValueLoading协议。)

    您可以使用测试是否为属性加载了值statusOfValueForKey:error:。首次加载asset时,其大部分或全部属性的值为AVKeyValueStatusUnknown。要为一个或多个属性加载值,请调用loadValuesAsynchronouslyForKeys:completionHandler:。在完成处理程序中,您可以根据属性的状态采取适当的操作。您应该始终准备好使加载未成功完成,这是由于加载由于某种原因而失败,例如基于网络的URL无法访问,或者因为加载被取消。

    NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;
    AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
    NSArray *keys = @[@"duration"];
     
    [asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {
     
        NSError *error = nil;
        AVKeyValueStatus tracksStatus = [asset statusOfValueForKey:@"duration" error:&error];
        switch (tracksStatus) {
            case AVKeyValueStatusLoaded:
                [self updateUserInterfaceForDuration];
                break;
            case AVKeyValueStatusFailed:
                [self reportError:error forAsset:asset];
                break;
            case AVKeyValueStatusCancelled:
                // Do whatever is appropriate for cancelation.
                break;
       }
    }];
    

    如果要准备播放资产,则应加载其tracks属性。 有关播放资产的更多信息,请参见playback

    从视频获取静止图像

    要从asset中获取诸如缩略图之类的静止图像进行播放,请使用一个AVAssetImageGenerator对象。您可以使用asset初始化图像生成器。即使初始化时asset没有视觉轨迹,初始化也可能会成功,因此如有必要,您应该使用来测试asset是否具有视觉特性的轨迹tracksWithMediaCharacteristic:。

    AVAsset anAsset = <#Get an asset#>;
    if ([[anAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0) {
    AVAssetImageGenerator *imageGenerator =
        [AVAssetImageGenerator assetImageGeneratorWithAsset:anAsset];
    // Implementation continues...
    }
    

    你可以配置图像生成器的多个方面,例如,你可以分别使用maximumSizeapertureMode指定它生成的图像的最大尺寸和aperture模式。然后,你可以在给定时间生成单个图像,或者一系列图片。你必须确保在生成所有图像之前保留对图像生成器的强引用。

    生成单个图像

    你使用copyCGImageAtTime:actualTime:error:在特定时间生成单个图像。 AVFoundation可能无法在你请求的时间生成图像,因此你可以将指向CMTime的指针作为第二个参数传递,返回时包含实际生成图像的时间。

    
    //获取静态图片(可以取得视频中某个时刻的图片)
    NSURL *url = [NSURL  URLWithString:@"http://vfx.mtime.cn/Video/2019/03/19/mp4/190319222227698228.mp4"];
    AVAsset *asset = [AVAsset assetWithURL:url];
    
    UIImage *image = nil;
    if ([[asset tracksWithMediaType:AVMediaTypeVideo] count]>0) {
        AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    
    
        //CMTimeMakeWithSeconds(x,y)  x第几秒的截图,y首选的时间尺度 "每秒的帧数
        Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
        NSLog(@"aaa = %f",durationSeconds/2.0);
        
        /*
        CMTime CMTimeMake (
            int64_t value,    //表示 当前视频播放到的第几桢数
            int32_t timescale //每秒的帧数
        );
        
        CMTime CMTimeMakeWithSeconds(
            Float64 seconds,   //第几秒的截图,是当前视频播放到的帧数的具体时间
            int32_t preferredTimeScale //首选的时间尺度 "每秒的帧数"
        );
        */
        CMTime midpoint = CMTimeMakeWithSeconds(1.5, 600);
        NSError *error;
        CMTime actualTime;
    
        CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
    
        if (halfWayImage != NULL) {
            image = [UIImage imageWithCGImage:halfWayImage];
            // Do something interesting with the image.
            CGImageRelease(halfWayImage);
     
            NSLog(@"image = %@",image);
        }
    }
    
    

    生成图像序列

    要生成一系列图像,请向图像生成器发送一条generateCGImagesAsynchronouslyForTimes:completionHandler:消息。第一个参数是一个NSValue对象数组,每个对象都包含一个CMTime结构,用于指定要为其生成图像的资产时间。第二个参数是一个块,用作为每个生成的图像调用的回调。块参数提供一个结果常量,该常量告诉您是否成功创建了映像或是否取消了操作,并根据需要:

    • 图片
    • 您请求图像的时间以及生成图像的实际时间
    • 描述错误生成原因的错误对象

    在Block的实现中,检查结果常量以确定是否创建了图像。另外,请确保对图像生成器保持强烈的引用,直到它完成创建图像为止。

    AVAsset *myAsset = <#An asset#>];
    // Assume: @property (strong) AVAssetImageGenerator *imageGenerator;
    self.imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:myAsset];
     
    Float64 durationSeconds = CMTimeGetSeconds([myAsset duration]);
    CMTime firstThird = CMTimeMakeWithSeconds(durationSeconds/3.0, 600);
    CMTime secondThird = CMTimeMakeWithSeconds(durationSeconds*2.0/3.0, 600);
    CMTime end = CMTimeMakeWithSeconds(durationSeconds, 600);
    NSArray *times = @[NSValue valueWithCMTime:kCMTimeZero],
                      [NSValue valueWithCMTime:firstThird], [NSValue valueWithCMTime:secondThird],
                      [NSValue valueWithCMTime:end]];
     
    [imageGenerator generateCGImagesAsynchronouslyForTimes:times
                    completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime,
                                        AVAssetImageGeneratorResult result, NSError *error) {
     
                    NSString *requestedTimeString = (NSString *)
                        CFBridgingRelease(CMTimeCopyDescription(NULL, requestedTime));
                    NSString *actualTimeString = (NSString *)
                        CFBridgingRelease(CMTimeCopyDescription(NULL, actualTime));
                    NSLog(@"Requested: %@; actual %@", requestedTimeString, actualTimeString);
     
                    if (result == AVAssetImageGeneratorSucceeded) {
                        // Do something interesting with the image.
                    }
     
                    if (result == AVAssetImageGeneratorFailed) {
                        NSLog(@"Failed with error: %@", [error localizedDescription]);
                    }
                    if (result == AVAssetImageGeneratorCancelled) {
                        NSLog(@"Canceled");
                    }
      }];
    

    您可以通过向图像生成器发送一条cancelAllCGImageGeneration消息来取消图像序列的生成。

    剪辑影片并进行转码

    您可以使用AVAssetExportSession对象将电影从一种格式转码为另一种格式,并修剪电影。工作流程如图1-1所示。导出会话是一个控制器对象,用于管理资产的异步导出。您可以使用您要导出的资产和一个导出预设的名称(表示您要应用的导出选项allExportPresets)来初始化会话(请参阅参考资料)。然后,您可以配置导出会话以指定输出URL和文件类型,以及其他可选设置,例如元数据以及是否应针对网络使用优化输出。

    [站外图片上传中...(image-2c8213-1589857008151)]

    AVAsset *anAsset = <#Get an asset#>;
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
            initWithAsset:anAsset presetName:AVAssetExportPresetLowQuality];
        // Implementation continues.
    }
    

    您可以使用exportPresetsCompatibleWithAsset:以下示例检查是否可以使用给定预设导出给定资产:

    exportSession.outputURL = <#A file URL#>;
        exportSession.outputFileType = AVFileTypeQuickTimeMovie;
     
        CMTime start = CMTimeMakeWithSeconds(1.0, 600);
        CMTime duration = CMTimeMakeWithSeconds(3.0, 600);
        CMTimeRange range = CMTimeRangeMake(start, duration);
        exportSession.timeRange = range;
    

    您可以通过提供输出URL(URL必须是文件URL)AVAssetExportSession来完成会话的配置。可以从URL的路径扩展名推断输出文件的类型。通常,您可以直接使用进行设置outputFileType。您还可以指定其他属性,例如时间范围,输出文件长度的限制,是否应针对网络使用优化导出的文件以及视频组成。下面的示例说明如何使用该timeRange属性修剪影片:

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
     
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed:
                    NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                    break;
                case AVAssetExportSessionStatusCancelled:
                    NSLog(@"Export canceled");
                    break;
                default:
                    break;
            }
        }];
    

    要创建新文件,请调用exportAsynchronouslyWithCompletionHandler:。导出操作完成时,将调用完成处理程序块;在处理程序的实现中,应检查会话的status值以确定导出是成功,失败还是被取消:

    您可以通过向会话发送cancelExport消息来取消导出。

    如果您尝试覆盖现有文件或在应用程序的沙箱外部写入文件,则导出将失败。在以下情况下也可能会失败:

    有打来的电话
    您的应用程序在后台,另一个应用程序开始播放
    在这些情况下,通常应通知用户导出失败,然后允许用户重新启动导出。

    相关文章

      网友评论

          本文标题:AVFoundation编程指南(二)

          本文链接:https://www.haomeiwen.com/subject/ocbvohtx.html