How to play video from NSData

女生的网名这么多〃 提交于 2019-12-18 02:49:25

问题


I would like to know if it's possible to play a video from an NSData object... with the MPMoviePlayerController.


回答1:


Ben's answer works perfectly on simulator but wont work on the device, You cannot write anywhere on the device. Check code below

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



回答2:


As far as I know this is not possible. If the data comes from your DB, can you save it into a temporary file and play that?




回答3:


It is better to use NSFileManager in this case instead 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];



回答4:


  1. create a file with the type of your NSData for example if your NSData is type of mp4 create a file with that type - for example - "myMove.mp4"

  2. copy past the file to your app resurces

  3. add this code

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


来源:https://stackoverflow.com/questions/5026620/how-to-play-video-from-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!