2011-10-21 18 views
3

我有這樣的代碼MPMoviePlayerViewController的作品,MPMoviePlayerController不..爲什麼?

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]; 

的第2部分的作品,第一部分不...他們使用的是相同的URL,我已經幾乎拷入和粘貼從ADC網站的片段

我使用ios5

+0

感謝包括2部分只看到了部分1代碼,它一直讓我發瘋,因爲它不起作用。第2部分代碼很好用! – scum

回答

-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]; 
    } 
} 
+0

MPMovieLoadStatePlayable == MPMovieLoadStatePlayable ??這是什麼? – applefreak

0

我有一個類似的問題在iOS 5 MPPlayerController和我已經檢查了蘋果的示例項目,差異只是設置幀,所以我手動設置幀和它完美地完成了。

[[[self moviePlayer] view] setFrame:CGRectMake(0, 0, 320, 480)]; 
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];   
} 
+0

這並不明顯 - 謝謝。 –

相關問題