MPMoviePlayerController doesn't play newly sav

2019-07-20 06:36发布

I'm using an imagePickerController to record video. In the imagePickerController:didFinishPickingMediaWithInfo: function I'm trying to set the video to a previously defined MPMoviePlayerController:

if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
    NSURL *movieUrl = [info objectForKey:UIImagePickerControllerMediaURL];
    [self.moviePlayer setContentURL:movieUrl]];
}

This is working fine and the video is indeed playing. But I want to save the file for later use. When I do this and use the saved file for the moviePlayer, nothing happens:

  • I've tried this (saving the data to a new file)

    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *newPath = [directory stringByAppendingPathComponent:@"myMovie.mov"];
    NSData *videoData = [NSData dataWithContentsOfURL:movieUrl];
    [videoData writeToFile:newPath atomically:NO];
    [self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
    
  • or this (copying the temp video file to my document folder)

    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *newPath = [directory stringByAppendingPathComponent:@"myMovie.mov"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    [fileManager copyItemAtPath:[videoUrl path] toPath:newPath error:&error];
    [self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];
    

Without any success, even though the file at newPath does exist... What am I doing wrong?

2条回答
劳资没心,怎么记你
2楼-- · 2019-07-20 06:46

use the code below:

NSData *movieData;  
    NSError *dataReadingError = nil;        
    movieData = [NSData dataWithContentsOfURL: movieURL options:NSDataReadingMapped error:&dataReadingError];        
    if(movieData != nil)        
        NSLog(@"Successfully loaded the data.");   
    else        
        NSLog(@"Failed to load the data with error = %@", dataReadingError); 
查看更多
Emotional °昔
3楼-- · 2019-07-20 07:05

Ok I finally found the issue. The problem was not in fact with the MPMoviePlayerController but with the line:

[self.moviePlayer setContentURL:[NSURL URLWithString:newPath]];

I fixed it by replacing that line with:

[self.moviePlayer setContentURL:[NSURL fileURLWithPath:newPath isDirectory:NO]];

Hope that will help someone else!

查看更多
登录 后发表回答