在iOS10 +播放结束后如何从锁屏消失播放器控件?

问题描述 投票:0回答:1

在后台模式下播放音频时,锁定屏幕上会出现播放器控件。如何在音频停止时将其删除?如果尝试设置:

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil

播放器仍然在锁屏上,但艺术家/歌曲的字段是空的

enter image description here

UPD(我的音频代码):

在AppDelegate中:

func setupAudioSession() {

    let audioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayback)
        try audioSession.setActive(true)

    } catch {
        print("Setting category to AVAudioSessionCategoryPlayback failed.")
    }
}

在Player类中:

private func clearRemotePlayerInfo() { // call after stop button pressed
    try? AVAudioSession.sharedInstance().setActive(false)
    MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
}
ios swift avaudiosession background-audio
1个回答
5
投票

TL; DR

关于Github的例子:https://github.com/JakubMazur/SO52243428


你不应该将nil分配给这个nowPlayingInfo

你应该做的是:

  1. 停止播放(没有必要,但清理你创建的内容很好)
  2. 将会话设置为无效
  3. 清除nowPlayingInfo

所以代码看起来像:

self.player?.stop() // Where self.player is AVAudioPlayer
try? self.session?.setActive(false, with: .notifyOthersOnDeactivation) // Where self.session is AVAudioSession. You should do it with do-catch to good error catching.
MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]

它会表现得像这样:

enter image description here

编辑:

我写了尽可能简单的例子来尝试一下。它可以在Github https://github.com/JakubMazur/SO52243428上找到。请随意查看它,它符合您的情况。

© www.soinside.com 2019 - 2024. All rights reserved.