13

我有一个 AVPlayer,每当单击链接时,我都会将其加载到新视图中。

-(void)createAndConfigurePlayerWithURL:(NSURL *)movieURL sourceType:(MPMovieSourceType)sourceType {
self.playerItem = [AVPlayerItem playerItemWithURL:movieURL];
customControlOverlay = [[AFDetailViewController alloc] initWithNibName:@"AFMovieScrubControl" bundle:nil];
backgroundWindow = [[UIApplication sharedApplication] keyWindow];
[customControlOverlay.view setFrame:backgroundWindow.frame];
[backgroundWindow addSubview:customControlOverlay.view];

playerLayer = [AVPlayerLayer playerLayerWithPlayer:[AVPlayer playerWithPlayerItem:playerItem]];
[playerLayer.player play];
playerLayer.frame = customControlOverlay.view.frame;
[customControlOverlay.view.layer addSublayer:playerLayer]; 
}

上面的代码将 AVPlayer 添加到我的应用程序中并且工作正常。我的 customControlOverlay 笔尖中有一个开关,它应该删除视图并停止播放 AVplayer。

-(IBAction)toggleQuality:(id)sender {
if (qualityToggle.selectedSegmentIndex == 0) {
    NSLog(@"HD");
    [playerLayer.player pause];
    [self.view removeFromSuperview];

} else if (qualityToggle.selectedSegmentIndex == 1) {
    NSLog(@"SD");
}
}

视图已正确删除,但播放器仍在后台播放。在测试了一下之后,玩家不会响应 toggleQuality 方法中的任何代码,但是我在那里的字符串作为检查被记录。

对我做错了什么有任何想法吗?

4

2 回答 2

27

我知道这是一个老问题,但有一天它可能会对某人有所帮助。

由于playerLayer被添加为 asublayer而不是 asubview它只需要从其超级层(而不是超级视图)中删除,并且播放器应设置为 nil,例如:

/* not sure if the pause/remove order would matter */
[playerLayer.player pause];
// uncomment if the player not needed anymore
// playerLayer.player = nil;
[playerLayer removeFromSuperlayer];
于 2014-10-20T15:12:07.683 回答
2

这是 Swift 中的答案。

就像@Paresh Navadiya 和@Yoga 在答案下方的评论中所说的那样。playerLayer 的玩家必须设置为 nil。playerLayer?.player = nil

在 viewWillDisappear 中添加代码:

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        player?.pause() // 1. pause the player to stop it
        playerLayer?.player = nil // 2. set the playerLayer's player to nil
        playerLayer?.removeFromSuperlayer() // 3 remove the playerLayer from its superLayer
}
于 2018-03-13T23:57:00.083 回答