问题 如何从NSData播放视频


大家好,我想知道是否可以使用MPMoviePlayerController从NSData对象播放视频。

谢谢,塞尔吉奥


3074
2018-02-17 08:32


起源

你从哪里获得数据? - zoul
从我的数据库...不是从包... - Sergio Andreotti


答案:


Ben的答案在模拟器上完美运行,但不能在设备上工作,你不能在设备上的任何地方写。检查下面的代码

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myMove.mp4"];

    [videoData writeToFile:path atomically:YES];
    NSURL *moveUrl = [NSURL fileURLWithPath:path];
    player = [[MPMoviePlayerController alloc]init];
    [player setContentURL:moveUrl];
    player.view.frame = viewPlayer.bounds;
    [viewPlayer addSubview:player.view];
    [player play];

14
2018-02-17 07:35



OPS!我不敢相信我刚回答了一个一岁的问题...... :) - drexsien
我想知道如果没有写入文件有没有办法做到这一点? - Hope4You
[[NSFileManager defaultManager] createFileAtPath:videoPath contents:videoData attributes:nil]; - Zeeshan


据我所知,这是不可能的。如果数据来自您的数据库,您可以将其保存到临时文件中并播放吗?


0
2018-02-17 09:30



是的,但我想避免这种情况......;)我现在正试图用QTKit框架做到这一点...... - Sergio Andreotti
但它不起作用... uff :( - Sergio Andreotti
2595063 stackoverflow - Sergio Andreotti


在这种情况下,最好使用NSFileManager而不是writeToFile

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myMove.mp4"];

[[NSFileManager defaultManager] createFileAtPath:path contents:videoData attributes:nil];

NSURL *moveUrl = [NSURL fileURLWithPath:path];
player = [[MPMoviePlayerController alloc]init];
[player setContentURL:moveUrl];
player.view.frame = viewPlayer.bounds;
[viewPlayer addSubview:player.view];
[player play];

0
2017-09-09 03:54



使用createFileAtPath和writeToFile有什么好处? - user523234


  1. 创建一个具有NSData类型的文件,例如,如果您的NSData是mp4类型,则创建具有该类型的文件 - 例如 - “myMove.mp4”

  2. 复制过去的文件到您的应用程序resurces

  3. 添加此代码

    NSData *mediaData; //your data    
    NSString *movePath=[[NSBundle mainBundle] pathForResource:@"myMove" ofType:@"mp4"];         
    [mediaData writeToFile:movePath atomically:YES];        
    NSURL *moveUrl= [NSURL fileURLWithPath:movePath];    
    MPMoviePlayerController *movePlayer=[[MPMoviePlayerController alloc]init];          
    [movePlayer setContentURL:moveUrl]; 
    [movePlayer play];
    

-4
2018-06-13 17:51



这不适用于设备,您无法在设备上的任何位置写入文件。看看下面的答案.. - drexsien
-1用于改变宗教信仰 - Brad Thomas