我有一个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方法中的任何代码做出响应,但是我在那里的字符串会被记录。
对我做错了什么的想法?
答案 0 :(得分:21)
我知道这是一个老问题,但有一天它可能对某人有所帮助。
由于 playerLayer 被添加为sublayer
而不是subview
,因此只需将其从其超级层(而非超级视图)和播放器中删除应该设置为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];
答案 1 :(得分:0)
以下是Swift的答案。
就像@Paresh Navadiya和@Yoga在下面的评论中所说的那样。 playerLayer的玩家必须设置为零。 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 it's superLayer
}