开发者

How to play video from NSData

I would like to know if it's possible to play a video from an NSData object... with the MPMoviePlayer开发者_Go百科Controller.


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


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?


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜