How to play video from NSData

2019-01-23 06:49发布

问题:

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

Thanks in advance, Sergio

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