我正在我的iPad应用程序中实现一些视频,并且效果很好。但是我遇到的问题是,当我离开视图导航到其他地方时,视频音频会继续在后台播放。有没有办法在关闭视图之前完全停止视频并将其从视图中删除?

我试过了:

[moviePlayerController stop]; -但这似乎并不能阻止电影,只会使应用程序崩溃。

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

最佳答案

如果我正确地关注您,则应在-viewWillDisappear:中停止影片播放器控制器。

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


编辑刚注意到,您正在创建MPMoviePlayerViewController而不是MPMoviePlayerController。前者是模态显示的,因为它是UIViewController的子类。这解释了崩溃,因为MPMoviePlayerViewController不响应-stop消息。因此,要么将moviePlayerController-presentModalViewController:animated:一起显示,要么将其类型更改为MPMoviePlayerController,然后将其添加到视图中即可。

10-05 21:57