我使用AVQueuePlayer
做在我们的应用程序的视频列表的播放。 我试图缓存由播放的视频AVQueuePlayer
使得视频不必每次都下载。
因此,在视频播放完之后,我尝试将AVPlayerItem保存到它与本地URL初始化磁盘,以便下一次。
我试图通过两种途径来实现:
- 使用AVAssetExportSession
- 使用AVAssetReader和AVAssetWriter。
1)的方法AVAssetExportSession
这种方法是这样的:
- 当观察
AVPlayerItem
结束使用打AVPlayerItemDidPlayToEndTimeNotification
。 - 当收到上述通知(视频播放完毕,所以它完全下载),使用
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'' ***
任何帮助深表感谢。