我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''
***
任何帮助深表感谢。