MPMoviePlayerViewController工作,MPMoviePlayerController没有..为什么?

时间:2011-10-21 14:31:21

标签: iphone media-player ios5

我有这段代码

NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"d" ofType:@"mp4"];  
NSURL    *url    =   [NSURL fileURLWithPath:filepath];  

//part 1
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: url];
[player.view setFrame: self.view.bounds];  
//[player prepareToPlay];
//[player setShouldAutoplay:YES];
//[player setControlStyle:2];
[self.view addSubview: player.view];
[player play];

//part2
MPMoviePlayerViewController *mp = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[[mp moviePlayer] prepareToPlay];
[[mp moviePlayer] setShouldAutoplay:YES];
[[mp moviePlayer] setControlStyle:2];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoPlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:mp];
[self presentMoviePlayerViewControllerAnimated:mp];

part2有效,第1部分没有......他们使用相同的网址,我几乎从ADC网站上复制并粘贴了代码段

我正在使用ios5

3 个答案:

答案 0 :(得分:1)

这个问题发布已经很久了,但答案是你必须保留MPMoviePlayerController变量的引用。

如果您在函数中有part1的代码,请在.h文件中声明MPMoviePlayerController *player。如果你不这样做(并且你正在使用ARC开发),那么退出该函数后,你的播放器变量将被解除分配。请注意,您正在向player.view添加self.view,因此播放器的视图会被保留,但播放器的控制器不会被取消分配。

所以你应该在你的.h文件中:

MPMoviePlayerController *player;

在这种情况下,你的功能必须是:

-(void) playMovie
{
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                         pathForResource:@"mymovie" 
                                         ofType:@"mov"]];    

    player = [[MPMoviePlayerController alloc] initWithContentURL: url];
    [player.view setFrame: self.view.bounds];  
    [self.view addSubview: player.view];
    [player play];        
}

答案 1 :(得分:0)

我在使用MPPlayerController的iOS 5上遇到了类似的问题,我检查了Apple的示例项目,不同之处仅在于设置框架,因此我手动设置框架并且工作正常。

    [[[self moviePlayer] view] setFrame:CGRectMake(0, 0, 320, 480)];

答案 2 :(得分:-1)

在未加载视频之前,您无法将播放器视图添加到主视图中。

所以你应该替换这一行:

[self.view addSubview: player.view];

通过这个:

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(movieLoadStateDidChange:) 
    name:MPMoviePlayerLoadStateDidChangeNotification 
    object:player];

并添加此方法:

-(void)movieLoadStateDidChange: (NSNotification*)notification{
    if (player.loadState & MPMovieLoadStatePlayable == MPMovieLoadStatePlayable) {
        [[NSNotificationCenter defaultCenter] 
            removeObserver:self 
            name:MPMoviePlayerLoadStateDidChangeNotification 
            object:player] ; 
        [self.view addSubview:player.view];
    }
}