如何从coredata作为nsdata formate在AVPlayer中播放视频?MPMoviePlayerController已弃用,所以我要使用AVPlayer。我正在搜索关于保存的nsdata位置的URL路径的一些信息,我不清楚。有人解释吗?我怎么玩?
对此我是新手,如果能共享该代码,我将不胜感激。
如果有人共享自定义AVPlayer的好教程,我找不到很好的教程,所以请从github示例项目中学习。
预先感谢:)
您可以尝试这个!
NSString *filePath = [self documentsPathForFileName:@"video.mp4"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if(!fileExists) {
NSData *videoAsData; // your data here
[videoAsData writeToFile:filePath atomically:YES];
}
// access video as URL
NSURL *videoFileURL = [NSURL fileURLWithPath:filePath];
// create an AVPlayer
AVPlayer *player = [AVPlayer playerWithURL:videoFileURL];
// create a player view controller
AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
controller.player = player;
[self presentViewController:controller animated:YES completion:^{
[controller.player play];
}];
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
// if you want to remove file after playing video
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
这是有关如何执行此操作的Swift版本
let data = //... your video Data/NSData
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("yourvidename.mp4")
do {
try data.write(to: cacheURL, options: .atomicWrite)
} catch let err {
print("Failed with error:", err.localizedString)
}
// instantiate the player
let player = AVPlayer(url: cacheURL)
let vcPlayer = AVPlayerViewController()
vcPlayer.player = player
vcPlayer.player?.play()
// present it or add it to whatever view you need
present(vcPlayer, animated: true, completion: nil)
然后根据需要删除viewWillDisappear
上的内容