MPMoviePlayerController无法正常工作

时间:2013-04-12 09:44:29

标签: objective-c mpmovieplayercontroller

我正在制作一个我试图播放视频的应用程序。视频正常启动,但视频屏幕在4秒后变为黑色。我不知道是什么问题。

当我设置player.movi​​eplayer.shouldautoplay = NO时,此行无效,视频会自动启动。

这是代码:

NSString *urlString = [[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"];

NSURL *urlObj = [NSURL fileURLWithPath:urlString];

UIGraphicsBeginImageContext(CGSizeMake(1,1));
MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:urlObj];
UIGraphicsEndImageContext();

[player.view setBounds:self.view.bounds];
// when playing from server source type shoud be MPMovieSourceTypeStreaming
[player.moviePlayer setMovieSourceType:MPMovieSourceTypeStreaming];
[player.moviePlayer setScalingMode:MPMovieScalingModeAspectFill];

player.moviePlayer.shouldAutoplay =  NO;

[self.view addSubview:player.view];
[player.moviePlayer play];

我在这里错过了什么吗?

我试图获取视频的总持续时间(使用mpmovieplayercontroller的持续时间属性),但显示为0.0。如何获得视频的持续时间?

2 个答案:

答案 0 :(得分:4)

NSString *urlString = [[NSBundle mainBundle] pathForResource:@"Movie" ofType:@"m4v"];
NSURL *urlObj = [NSURL fileURLWithPath:urlString];

UIGraphicsBeginImageContext(CGSizeMake(1,1));
MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:urlObj];
UIGraphicsEndImageContext();

[player.view setBounds:self.view.bounds];
// when playing from server source type shoud be MPMovieSourceTypeStreaming
[player.moviePlayer setMovieSourceType:MPMovieSourceTypeStreaming]; // I was missing this line therefore video was not playing
[player.moviePlayer setScalingMode:MPMovieScalingModeAspectFill];


[self.view addSubview:player.view];
[player.moviePlayer play];

答案 1 :(得分:2)

这里有几个问题:

  1. 对于此类用法(将播放器集成到您的视图中),您应该使用MPMoviePlayerController,而不是MPMoviePlayerViewController。如果您想拥有一个可以使用MPMoviePlayerViewController呈现的自包含视图控制器,请使用presentMoviePlayerViewControllerAnimated:

  2. 假设您正在使用ARC,主要问题是没有任何内容可以保留对您的播放器对象的引用。因此,玩家在创建后不久就会消失。您应该通过将其分配给视图控制器的属性或实例变量来保留对它的引用。

    有关此问题的完整示例,请参阅Till的优秀answer to a similar question

  3. 我不确定UIGraphicsBeginImageContextUIGraphicsEndImageContext来电的目的是什么,但我看不到他们在这里需要它们。


  4. 对于shouldAutoplay = NO,视频仍在启动,因为您之后会立即致电play


    播放器的duration属性仅在收到MPMovieDurationAvailableNotification后包含有用的值。您需要执行与以下类似的操作才能访问实际持续时间:

    __weak MediaPlayerController *weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:MPMovieDurationAvailableNotification object:self.player queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
      NSLog(@"Movie duration: %lf", weakSelf.player.duration);
    }];
    

    完成后使用removeObserver:name:object:删除观察者。