MPMoviePlayerController: Not playing video

Refresh

December 2018

Views

3.3k time

2

I'm trying to use the MPMoviePlayerController to play a locally saved video however it is not working.

Here's my source:

self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[self.moviePlayer prepareToPlay];

CGRect frame = self.movieView.frame;
frame.origin = CGPointZero;

self.moviePlayer.view.frame = frame;

self.moviePlayer.allowsAirPlay         = NO;
self.moviePlayer.shouldAutoplay        = NO;
self.moviePlayer.movieSourceType       = MPMovieSourceTypeFile;
self.moviePlayer.scalingMode           = MPMovieScalingModeAspectFit;
self.moviePlayer.controlStyle          = MPMovieControlStyleEmbedded;
self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

[self.movieView addSubview:self.moviePlayer.view];

It does work when I have a URL like "assets-library://asset/asset.MOV?id=2C7D89F6-2211-4920-A842-30D773B075D6&ext=MOV" but when I have a URL like "file:///var/mobile/Media/DCIM/101APPLE/IMG_1454.mp4" it doesn't work.

I'm using the below code to get the users latest video and play it in the player:

- (void)mostRecentVideo:(void (^)(NSURL *url))completion
{
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:fetchOptions];
PHAsset *lastAsset = [fetchResult lastObject];

PHVideoRequestOptions *options = [PHVideoRequestOptions new];
options.deliveryMode = PHVideoRequestOptionsDeliveryModeMediumQualityFormat;

[[PHImageManager defaultManager] requestAVAssetForVideo:lastAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
    if ([asset isKindOfClass:[AVURLAsset class]])
        completion(((AVURLAsset *)asset).URL);
}];
}

4 answers

0

Я сделал некоторые изменения в коде и поместить фильм код игрока в PHImageManager блоке и его работу для меня.

      [[PHImageManager defaultManager] requestAVAssetForVideo:lastAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
            if ([asset isKindOfClass:[AVURLAsset class]])
                NSLog(@"%@",((AVURLAsset *)asset).URL);

            AVURLAsset *assetURL = [AVURLAsset assetWithURL:((AVURLAsset *)asset).URL];

            NSString *str= [NSString stringWithFormat:@"%@",assetURL.URL];

            NSURL *url = [NSURL URLWithString:str];

            // Initialize the MPMoviePlayerController object using url
            _videoPlayer =  [[MPMoviePlayerController alloc]
                             initWithContentURL:url];

            [_videoPlayer.view setFrame:CGRectMake(0, 0, 320, 568)];

            // Add a notification. (It will call a "moviePlayBackDidFinish" method when _videoPlayer finish or stops the plying video)
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(moviePlayBackDidFinish:)
                                                         name:MPMoviePlayerPlaybackDidFinishNotification
                                                       object:_videoPlayer];

            // Set control style to default
            _videoPlayer.controlStyle = MPMovieControlStyleDefault;

            // Set shouldAutoplay to YES
            _videoPlayer.shouldAutoplay = YES;
            [_videoPlayer setMovieSourceType:MPMovieSourceTypeFile];

            // Add _videoPlayer's view as subview to current view.
            [self.view addSubview:_videoPlayer.view];

            // Set the screen to full.
            [_videoPlayer setFullscreen:YES animated:YES];

        }];

Пожалуйста, проверьте, если он может помочь вам ...

1

Я предполагаю , что вы используете NSUrl *url = [NSURL URLWithString:urlStr];для urlв

self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

Но с Filepath как: file:///var/mobile/Media/DCIM/101APPLE/IMG_1454.mp4 вы должны использовать:

NSUrl *url =  [NSURL fileURLWithPath:filePath];

См NSURL документ

0

Я сделал некоторые изменения в коде и поместить фильм код игрока в PHImageManager блоке и его работу для меня.

      [[PHImageManager defaultManager] requestAVAssetForVideo:lastAsset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
            if ([asset isKindOfClass:[AVURLAsset class]])
                NSLog(@"%@",((AVURLAsset *)asset).URL);

            AVURLAsset *assetURL = [AVURLAsset assetWithURL:((AVURLAsset *)asset).URL];

            NSString *str= [NSString stringWithFormat:@"%@",assetURL.URL];

            NSURL *url = [NSURL URLWithString:str];

            // Initialize the MPMoviePlayerController object using url
            _videoPlayer =  [[MPMoviePlayerController alloc]
                             initWithContentURL:url];

            [_videoPlayer.view setFrame:CGRectMake(0, 0, 320, 568)];

            // Add a notification. (It will call a "moviePlayBackDidFinish" method when _videoPlayer finish or stops the plying video)
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(moviePlayBackDidFinish:)
                                                         name:MPMoviePlayerPlaybackDidFinishNotification
                                                       object:_videoPlayer];

            // Set control style to default
            _videoPlayer.controlStyle = MPMovieControlStyleDefault;

            // Set shouldAutoplay to YES
            _videoPlayer.shouldAutoplay = YES;
            [_videoPlayer setMovieSourceType:MPMovieSourceTypeFile];

            // Add _videoPlayer's view as subview to current view.
            [self.view addSubview:_videoPlayer.view];

            // Set the screen to full.
            [_videoPlayer setFullscreen:YES animated:YES];

        }];

Пожалуйста, проверьте, если он может помочь вам ...

2

Тот же самый код работает для меня, я использовал его , как это. После получения URL - адреса является асинхронной операцией, он является обязательным для обновления пользовательского интерфейса на основную очереди. Просто поместите код viewDidAppearи повторите попытку.

[self mostRecentVideo:^(NSURL *url){
    NSLog(@"did play!, url is %@",url);
    self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    [self.moviePlayer prepareToPlay];

    CGRect frame = self.view.frame;
    frame.origin = CGPointZero;

    self.moviePlayer.view.frame = frame;

    self.moviePlayer.allowsAirPlay         = NO;
    self.moviePlayer.shouldAutoplay        = NO;
    self.moviePlayer.movieSourceType       = MPMovieSourceTypeFile;
    self.moviePlayer.scalingMode           = MPMovieScalingModeAspectFit;
    self.moviePlayer.controlStyle          = MPMovieControlStyleEmbedded;
    self.moviePlayer.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.view addSubview:self.moviePlayer.view];
    });
    [self.moviePlayer play];
}];