学习笔记- AVFoundation Programming Guide - Using Assets

来源:互联网 发布:火绒安全软件怎么样 编辑:程序博客网 时间:2024/06/05 18:03

Using Assets

Assets 能来自一个文件或者来自用户iPos库或照片库的多媒体文件。当你创建一个asset 对象时,所有你可能要检索的信息不是立即可用的。

一旦你有了一个视频asset,你可以提取静态图像,转换成另一种格式,或内容裁减。


1. Creating an Asset Object

通过URL创建asset,可以试用AVURLAsset。创建asset最简单的方式是通过一个文件。

code:

NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;
AVURLAsset *anAsset = [[AVURLAsset alloc] initWithURL:url options:nil];


2. Options for Initalizing an Asset

AVURLAsset初始化方法的第二个参数使用一个dictionary,这个dictionary里的唯一一个key是 AVURLAssetPreferPreciseDurationAndTimingKey。它的value是一个boolean类型(用NSValue包装的对象),这个值表示asset是否提供一个精确的duration。
获取asset精确的duration需要很多处理时间,使用一个预估的duration效率比较高并且对播放来说足够。因此:
. 如果你想要播放asset,初始化方法传nil就行了,而不是一个dictionry,或者传一个以AVURLAssetPreferPreciseDurationAndTimingKeydictionary为key,值为NO的一个dictionary。
. 如果你想把asset加到一个composition中,你需要一个精确的访问权限,这时你可以传一个dictionary,这个dictionary的一组键值对为AVURLAssetPreferPreciseDurationAndTimingKey和YES。
code:

NSURL *url = <#A URL that identifies an audiovisual asset such as a movie file#>;
NSDictionary *options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES };
AVURLAsset *anAssetToUseInAComposition = [[AVURLAsset alloc] initWithURL:url options:options];


3. Accessing the User's Assets

为了访问iPod Library 和相册里的asset,需要获取asset 的URL。

. 为了访问iPod Library,需要创建MPMediaQuery对象来找到想要的对象,然后通过MPMediaItemPropertyAssetURL获取它的URL。

. 为了访问相册,可以试用ALAssetsLibrary。

code:

// 下面的代码用来获取相册里面的第一个视频

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
 
// Within the group enumeration block, filter to enumerate just videos.
[group setAssetsFilter:[ALAssetsFilter allVideos]];
 
// For this example, we're only interested in the first item.
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:0]
                        options:0
                     usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
 
                         // The end of the enumeration is signaled by asset == nil.
                         if (alAsset) {
                             ALAssetRepresentation *representation = [alAsset defaultRepresentation];
                             NSURL *url = [representation url];
                             AVAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
                             // Do something interesting with the AV asset.
                         }
                     }];
                 }
                 failureBlock: ^(NSError *error) {
                     // Typically you should handle an error more gracefully than this.
                     NSLog(@"No groups");
                 }];


4. Preparing an Asset for Use

初始化一个asset(或者track)并不是表示asset里面所有的信息都是马上可用的。它需要一些时间去计算,即使是durtation(比如没有摘要信息的mp3文件),你应该使用AVAsynchronousKeyValueLoading协议获取这些值,通过- loadValuesAsynchronouslyForKeys:completionHandler:在handler里面获取你要的值。
你可以用statusOfValueForKey:error:测试一个属性的value是否成功获取,当一个assert第一次被加载,大多数属性的值是AVKeyValueStatusUnknown状态,为了获取一个或多个属性的值,你要调用loadValuesAsynchronouslyForKeys:completionHandler:,在comletiton handler里面,你可以根据属性的状态做任何合适的处理。你要处理加载没有成功的情况,可能因为一些原因比如网络不可连接,又或者loading被取消。

code:

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;
   }
}];


5. Getting Still Images From a Video

从播放的asset中获取静态图片比如缩略图,你可以用AVAssetImageGenerator对象。

可以用asset初始化一个AVAssetImageGenerator对象。即使asset在初始化的时候没有可见的track也能成功,所以你应该检测asset是否有track,使用tracksWithMediaCharacteristic:

code:

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

你还可以设置imagegenerator的其他属性,比如,你可以指定生成图片的最大的分辨率,你可以生成指定时间的一张图片,或者一系列图片。你必须一直持有generator的引用,直到生成所有的图片。


6. Generating a Single Image

你可以使用copyCGImageAtTime:actualTime:error:生成一张指定时间点的图片。AVFoundation不一定能精确的生成一张你所指定时间的图片,所以你可以在第二个参数传一个CMTime的指针,用来获取所生成图片的精确时间。

code:

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);
}


7. Generating a Sequence of Images

为了生成一系列图片,你可以调用generateCGImagesAsynchronouslyForTimes:completionHandler:。第一个参数是一个包含NSValue类型的数组,数组里每一个对象都是CMTime结构体,表示你想要生成的图片在视频中的时间点,第二个参数是一个block,每生成一张图片都会回调这个block,这个block提供一个result的参数告诉你图片是否成功生成或者图片生成操作是否取消。

在你的block实现中,需要检查result,判断image是否成功生成,另外,确保你持有image generator直到生成图片的操作结束。

code:

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消息取消生成图片序列的操作。


8. Trimming and Transcoding a Movie

你可以对视频进行转码、裁剪,通过使用AVAssetExportSession对象。

一个export session是一个控制对象,可以异步的生成一个asset。可以用你需要生成的asset和presetName来初始化一个session,presetName指明你要生成的asset的属性。接下来你可以配置export session,比如可以指定输出的URL和文件类型,以及其他的设置,比如metadata和是否输出应优化网络试用。
你可以先检测设置的preset是否可用,通过使用exportPresetsCompatibleWithAsset:方法。

code:

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

你可以配置session的输出的url(这个url必须是文件url),AVAssetExportSession可以通过url的扩展名推断出输出文件的类型。当然,你可以直接设置文件类型,使用outputFileType。你还可以指定其他属性,比如time range,输出文件的长度,是否应该对导出的文件进行网络优化,以及视频合成。

code:

// 试用时间范围修剪视频

    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;

生成一个新的asset,可以调用exportAsynchronouslyWithCompletionHandler:,当生成操作结束后会回调block,在这个block中你需要通过检查session的status来判断是否成功,如下:

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


你可以取消这个生成操作,通过给session发送 cancelExport 消息。
如果导出的文件存在,或者导出的url在沙盒之外,这个导出操作会失败。还有两种情况也可能导致失败:
· 来了一个电话
· 你的程序在后台运行并且其他的应用开始播放。
这种情况下,你应该通知用户export失败,并且重新export。



0 0
原创粉丝点击