0

我正在制作一个我正在尝试播放视频的应用程序。视频正常启动,但 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。如何获得视频的时长?

4

2 回答 2

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];
于 2013-04-12T09:50:16.110 回答
2

这里有几个问题:

  1. 对于这种类型的用法(将播放器集成到您的视图中),您应该使用MPMoviePlayerController,而不是MPMoviePlayerViewController. MPMoviePlayerViewController当您想拥有一个可以使用presentMoviePlayerViewControllerAnimated:.

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

    有关这方面的完整示例,请参阅Till对类似问题的出色回答

  3. 我不确定你的UIGraphicsBeginImageContextandUIGraphicsEndImageContext调用的预期目的是什么,但我看不出这里需要它们。


至于,视频还在开始,因为你马上就shouldAutoplay = NO打电话了。play


玩家的属性仅在收到durationa 后才包含有用的值。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:移除观察者。

于 2013-04-14T13:10:06.563 回答