2011-12-20 78 views
0

我正在實施一些視頻到我的iPad應用程序,它的工作正常。但我遇到的問題是,當我離開視圖導航到其他地方時,視頻音頻在後臺繼續播放。是否有辦法在關閉視圖之前完全停止視頻並將其從視圖中刪除?iOS媒體框架

我嘗試:

[moviePlayerController停車]; - 但這似乎並沒有阻止電影剛剛崩潰的應用程序。

[moviePlayerController.view removeFromSuperview]; - 從視圖中刪除視頻,但不會停止音頻。

這是我的代碼:

- (IBAction)PlayMediaButton:(id)sender 
{ 

[moviePlayerController stop]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) 
              name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; 

NSString *movpath = [[NSBundle mainBundle] pathForResource:@"albert" ofType:@"mp4"]; 
MPMoviePlayerViewController* mpviewController = [[MPMoviePlayerViewController alloc] 
               initWithContentURL:[NSURL fileURLWithPath:movpath]]; 

if ([[NSFileManager defaultManager] fileExistsAtPath:movpath])  //Does file exist? 
{ 
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:movpath]]; 

    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(moviePlaybackComplete:) 
               name:MPMoviePlayerPlaybackDidFinishNotification 
               object:moviePlayerController]; 

    moviePlayerController.view.frame = CGRectMake(38, 37, 986, 618); 
    [self.view addSubview:moviePlayerController.view]; 
    [moviePlayerController play]; 

    if ([moviePlayerController respondsToSelector:@selector(setAllowsAirPlay:)]) //Allow airplay if availabe 
     [moviePlayerController setAllowsAirPlay:YES]; 

    [moviePlayerController play]; 

}    
} 



- (void)moviePlaybackComplete:(NSNotification *)notification 
{ 
    MPMoviePlayerController *moviePlayerController = [notification object]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                name:MPMoviePlayerPlaybackDidFinishNotification 
                object:moviePlayerController]; 

    [moviePlayerController.view removeFromSuperview]; 
    [moviePlayerController release]; 
} 
+1

將'-stop'發送到'moviePlayerController'時,您收到了什麼錯誤?你在哪裏發送這條消息? – 2011-12-20 17:51:31

+0

粘貼你的代碼,顯示你如何創建'moviePlayerController'的實例,以及你試圖調用**'stop' **和**'removeFromSuperview' **的地方。 – WrightsCS 2011-12-20 17:52:02

+0

我添加了我必須調用視頻以及播放完成的時間。 – user964627 2011-12-20 17:54:35

回答

2

如果我正確地跟着你,你應該在-viewWillDisappear:停止電影播放器​​。

- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 
    [moviePlayerController stop]; 
} 

編輯只注意到你正在創建一個MPMoviePlayerViewController而不是MPMoviePlayerController的。前者是爲了模態顯示,因爲它是UIViewController的子類。這解釋了崩潰,因爲MPMoviePlayerViewController不響應-stop消息。因此,要麼將moviePlayerController-presentModalViewController:animated:一起顯示,要麼將其類型更改爲MPMoviePlayerController,並將其添加到您的視圖中,如同現在一樣。

+0

當我嘗試離開視圖時,試圖讓應用程序崩潰。 – user964627 2011-12-20 18:05:00

+0

是的,我們瞭解該應用程序崩潰。介意與我們分享您收到的錯誤? – 2011-12-20 18:07:09

+0

它似乎是停在main.m線程1上。 – user964627 2011-12-20 18:37:32