写在前面
正文
Assets可以来自文件,也可以来自于用户的iPod库或照片库中的媒体。当您创建一个asset对象时,您可能想要检索的所有信息并没有立即得到。一旦你有了电影asset,你就可以从它中提取静止的图像,将其转换成另一种格式,或者修改内容。
Creating an Asset Object(创建一个Asset对象)
NSURL *url = <#一个URL,用来标识诸如电影文件之类的视听asset#>;
AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
Options for Initializing an Asset(初始化asset的选项)
获取asset的确切时间可能需要大量的处理开销。使用近似持续时间通常是一个更便宜的操作和足够的回放。因此:
-
如果你只打算播放asset,通过nil而不是一本词典,或通过字典包含AVURLAssetPreferPreciseDurationAndTimingKey键和一个相应的值(包含在一个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图书馆,你创建一个
实例来找到你想要的商品,然后使用 得到它的URL。
有关媒体库的更多信息,请参阅Multimedia Programming Guide。
- 要访问由照片应用程序管理的asset,您可以使用。
下面的示例演示如何获得一个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以供使用)
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;
}
}];
Getting Still Images From a Video(从视频中获取静止图像)
AVAsset anAsset = <#Get an asset#>;
if ([[anAsset tracksWithMediaType:AVMediaTypeVideo] count] > 0) {
AVAssetImageGenerator *imageGenerator =
[AVAssetImageGenerator assetImageGeneratorWithAsset:anAsset];
// Implementation continues...
}
Generating a Single Image(生成一个图像)
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(生成一系列图像)
- 图像
- 您请求映像的时间和生成映像的实际时间
- 描述生成失败原因的错误对象
在你的程序块的实现中,检查结果常数,以确定图像是否被创建。此外,确保您对图像生成器有很强的引用,直到它完成创建图像为止。
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");
}
}];
Trimming and Transcoding a Movie(修剪和修改电影)
图1 - 1导出会话工作流你可以检查你是否可以导出一个给定的资产使用给定预设使用
如本例中所示:
AVAsset *anAsset = <#Get an asset#>;
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:anAsset presetName:AVAssetExportPresetLowQuality];
// Implementation continues.
}
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;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export canceled");
break;
default:
break;
}
}];
如果您试图覆盖现有的文件,或者在应用程序的沙箱之外编写文件,那么导出将会失败。如果:
- 有一个来电
- 您的应用程序在后台,另一个应用程序开始播放
在这些情况下,通常应该通知用户导出失败,然后允许用户重新启动导出。