How to play video from NSData

前端 未结 4 1917
长情又很酷
长情又很酷 2020-12-15 09:38

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

相关标签:
4条回答
  • 2020-12-15 10:29

    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];
    
    0 讨论(0)
  • 2020-12-15 10:30

    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];
    
    0 讨论(0)
  • 2020-12-15 10:31
    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 讨论(0)
  • 2020-12-15 10:36

    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?

    0 讨论(0)
提交回复
热议问题