如何在codata中播放AVPlayer中的视频为nsdata formate? 不推荐使用MPMoviePlayerController,所以我要使用AVPlayer。我正在搜索有关保存的nsdata位置的url路径的一些事情我不清楚。有谁解释这个?我怎么玩?
我是新手,我很感激,如果分享该代码。
如果有人为自定义AVPlayer分享了很好的教程我找不到好的教程,那么请从github示例项目中学习。
提前谢谢:)
答案 0 :(得分:1)
你可以试试这个!
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];
答案 1 :(得分:0)
这是有关如何执行此操作的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
上删除cachesDirectory
的内容