【问题标题】:Can't remove or stop AVPlayer无法删除或停止 AVPlayer
【发布时间】:2012-05-30 15:42:39
【问题描述】:

我有一个 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 方法中的任何代码,但是我在那里的字符串作为检查被记录下来。

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

【问题讨论】:

  • 使用 playerLayer.player = nil;在您从 superview 中删除之前
  • 即使我这样做,声音也会继续播放。
  • 如果你按其他顺序(删除然后设置为零)怎么办?
  • 尝试更改顺序,仍然无法删除。
  • 使用 playerLayer.player = nil;在您从 superview 中删除之前 应该是正确的答案。下面的答案对我不起作用。

标签: iphone ios ios5 avplayer


【解决方案1】:

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

由于 playerLayer 被添加为 sublayer 而不是 subview 它只需要从其超级层(而不是超级视图)中删除,并且播放器应设置为无,类似:

/* not sure if the pause/remove order would matter */
[playerLayer.player pause];
// uncomment if the player not needed anymore
// playerLayer.player = nil;
[playerLayer removeFromSuperlayer];

【讨论】:

  • 救了我的培根。谢谢。
  • 对不起,久违了。但是,我应该把下面的代码放在哪里?在viewDidDisappear: 或viewWillDisappear: 中?我都试过了,但都没有工作....你能帮帮我吗?提前致谢。
  • @Lilac 你有没有想过把这段代码放在哪里?
  • @JayQ。恐怕我没有使用这种方法来解决我的问题。它对我不起作用。
【解决方案2】:

这是 Swift 中的答案。

就像@Paresh Navadiya 和@Yoga 在答案下方的 cmets 中所说的那样。 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
}

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2019-10-18
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多