【发布时间】:2014-04-02 20:44:07
【问题描述】:
我正在使用AVQueuePlayer 播放我们应用中的视频列表。我正在尝试缓存AVQueuePlayer 播放的视频,以便不必每次都下载视频。
所以,视频播放完毕后,我会尝试将 AVPlayerItem 保存到磁盘中,以便下次使用本地 URL 对其进行初始化。
我尝试通过两种方法来实现这一点:
- 使用 AVAssetExportSession
- 使用 AVAssetReader 和 AVAssetWriter。
1) AVAssetExportSession 方法
这种方法的工作原理如下:
- 使用
AVPlayerItemDidPlayToEndTimeNotification观察AVPlayerItem何时完成播放。 - 收到上述通知后(视频播放完毕,因此已完全下载),使用
AVAssetExportSession将该视频导出到磁盘中的文件中。
代码:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
然后
- (void)videoDidFinishPlaying:(NSNotification*)note
{
AVPlayerItem *itemToSave = [note object];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:itemToSave.asset presetName:AVAssetExportPresetHighestQuality];
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.outputURL = [NSURL fileURLWithPath:@"/path/to/Documents/video.mp4"];
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch(exportSession.status){
case AVAssetExportSessionStatusExporting:
NSLog(@"Exporting...");
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"Export completed, wohooo!!");
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"Waiting...");
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"Failed with error: %@", exportSession.error);
break;
}
}
该代码在控制台中的结果是:
Failed with error: Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo=0x98916a0 {NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x99ddd10 "The operation couldn’t be completed. (OSStatus error -12109.)", NSLocalizedFailureReason=An unknown error occurred (-12109)}
2) AVAssetReader、AVAssetWriter 方法
代码:
- (void)savePlayerItem:(AVPlayerItem*)item
{
NSError *assetReaderError = nil;
AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:assetToCache error:&assetReaderError];
//(algorithm continues)
}
该代码在尝试使用以下信息分配/初始化 AVAssetReader 时引发异常:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVAssetReader initWithAsset:error:] Cannot initialize an instance of AVAssetReader with an asset at non-local URL 'https://someserver.com/video1.mp4''
***
非常感谢任何帮助。
【问题讨论】:
-
您找到解决方案了吗?我们现在遇到了同样的问题,我们不是试图缓存视频,而是编辑它们。我们已经通过在播放之前下载视频副本来解决此问题,但这显然很慢。
-
不,我们结束了手动将视频文件下载到磁盘并稍后在本地工作。
标签: ios avplayer avassetwriter avassetexportsession avassetreader