《AVFoundation》文档翻译 003 — 使用 Assets

写在前面

如果大家需要学习了解AVFoundation的可以关注我的专题《AVFounation官方稳当翻译》

正文

Assets可以来自文件,也可以来自于用户的iPod库或照片库中的媒体。当您创建一个asset对象时,您可能想要检索的所有信息并没有立即得到。一旦你有了电影asset,你就可以从它中提取静止的图像,将其转换成另一种格式,或者修改内容。

Creating an Asset Object(创建一个Asset对象)

创建一个asset来表示任何asset,你可以使用一个URL识别,您使用AVURLAsset
的。最简单的例子是从文件中创建asset:

NSURL *url = <#一个URL,用来标识诸如电影文件之类的视听asset#>;

AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];

Options for Initializing an Asset(初始化asset的选项)

AVURLAsset的初始化方法作为第二个参数的选项字典。本词典使用的唯一关键是 AVURLAssetPreferPreciseDurationAndTimingKey。对应的值是一个布尔值(包含在一个NSValue对象中),表示该asset是否应该准备好表示精确的持续时间,并按时间提供精确的随机访问。

获取asset的确切时间可能需要大量的处理开销。使用近似持续时间通常是一个更便宜的操作和足够的回放。因此:

  • 如果你只打算播放asset,通过nil而不是一本词典,或通过字典包含AVURLAssetPreferPreciseDurationAndTimingKey键和一个相应的值(包含在一个NSValue对象)。

  • 如果您想将asset添加到一个组合(AVMutableComposition
    ),您通常需要精确的随机访问。通过字典包含AVURLAssetPreferPreciseDurationAndTimingKey键和一个相应的值,是的(包含在一个NSValue object-recall NSNumber继承自NSValue):

    NSURL *url = <#一个URL,用来标识诸如电影文件之类的视听asset#>;
    NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES };
    AVURLAsset *anAssetToUseInAComposition = [[AVURLAsset alloc] initWithURL:url options:options];
    

Accessing the User’s Assets(访问用户的asset)

要访问由iPod库或照片应用程序管理的asset,您需要获得您想要的asset的URL。

  • 访问iPod图书馆,你创建一个MPMediaQuery
    实例来找到你想要的商品,然后使用 MPMediaItemPropertyAssetURL得到它的URL。

有关媒体库的更多信息,请参阅Multimedia Programming Guide。

  • 要访问由照片应用程序管理的asset,您可以使用ALAssetsLibrary。

下面的示例演示如何获得一个asset来表示保存的Photos相册中的第一个视频。

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

// 列举只是利用ALAssetsGroupSavedPhotos照片和视频组。

[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

// 在组枚举块中,筛选以枚举视频。

[group setAssetsFilter:[ALAssetsFilter allVideos]];

// 对于本例,我们只对第一项感兴趣。

[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:0]

options:0

usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {

// 枚举的末尾由asset = = nil表示。

if (alAsset) {

ALAssetRepresentation *representation = [alAsset defaultRepresentation];

NSURL *url = [representation url];

AVAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];

//做一些有趣的AV asset。

}

}];

}

failureBlock: ^(NSError *error) {

// 通常,您应该更优雅地处理一个错误。

NSLog(@"No groups");

}];

Preparing an Asset for Use(准备asset以供使用)

初始化asset(或跟踪)并不意味着您可能想要检索的所有信息都立即可用。它可能需要一些时间来计算一个条目的持续时间(例如,MP3文件可能不包含摘要信息)。而不是阻塞当前线程,而一个值被计算,你应该使用AVAsynchronousKeyValueLoading、 protocol _要求值,得到一个答案后通过使用一块完成处理器定义。(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;
}
}];

如果要为播放准备asset,应该加载其跟踪属性。有关播放asset的更多信息,请参见 Playback。

Getting Still Images From a Video(从视频中获取静止图像)

为了得到从一个asset的缩略图中得到的静态图像,你可以使用一个AVAssetImageGenerator
对象。您用您的asset初始化一个图像生成器。初始化可能会成功,即使asset拥有没有视觉跟踪初始化的时候,所以如果有必要你应该测试asset是否使用tracksWithMediaCharacteristic:。

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

您可以配置图像生成器的几个方面,例如,您可以分别指定其生成的图像的 maximumSize和使用apertureMode
。然后,您可以在给定的时间或一系列图像中生成单个图像。您必须确保您对图像生成器有很强的引用,直到它生成了所有的图像。

Generating a Single Image(生成一个图像)

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

AVAsset *myAsset = <#An asset#>];

AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset];

Float64 durationSeconds = CMTimeGetSeconds([myAsset duration]);

CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);

NSError *error;

CMTime actualTime;

CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

if (halfWayImage != NULL) {

NSString *actualTimeString = (NSString *)CMTimeCopyDescription(NULL, actualTime);

NSString *requestedTimeString = (NSString *)CMTimeCopyDescription(NULL, midpoint);

NSLog(@"Got halfWayImage: Asked for %@, got %@", requestedTimeString, actualTimeString);

// Do something interesting with the image.

CGImageRelease(halfWayImage);

}

Generating a Sequence of Images(生成一系列图像)

生成一系列的图像,你发送图像发生器generateCGImagesAsynchronouslyForTimes:completionHandler:
消息。第一个参数是一个NSValue对象数组,每个对象包含一个CMTime结构,指定要生成图像的资产时间。第二个参数是一个块,它充当为生成的每个映像调用的block 。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消息。

Trimming and Transcoding a Movie(修剪和修改电影)

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

《AVFoundation》文档翻译 003 — 使用 Assets_第1张图片
图1 - 1导出会话工作流

你可以检查你是否可以导出一个给定的资产使用给定预设使用 exportPresetsCompatibleWithAsset:
如本例中所示:

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

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

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;

创建新的文件,您调用 exportAsynchronouslyWithCompletionHandler:。当导出操作结束时调用完成处理block ;在执行处理程序时,应该检查会话的status,以确定导出是否成功、失败或被取消:

[exportSession exportAsynchronouslyWithCompletionHandler:^{

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

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

如果您试图覆盖现有的文件,或者在应用程序的沙箱之外编写文件,那么导出将会失败。如果:

  • 有一个来电
  • 您的应用程序在后台,另一个应用程序开始播放

在这些情况下,通常应该通知用户导出失败,然后允许用户重新启动导出。

下一页
上一页

你可能感兴趣的:(《AVFoundation》文档翻译 003 — 使用 Assets)