如何从NSData播放视频

时间:2011-02-17 08:32:49

标签: mpmovieplayercontroller nsdata playback

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

提前致谢,Sergio

4 个答案:

答案 0 :(得分:14)

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];

答案 1 :(得分:0)

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

答案 2 :(得分:0)

最好在这种情况下使用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];

答案 3 :(得分:-4)

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

  2. 将文件复制到您的应用程序后重新

  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];