swift 如何从锁屏消失播放器控制后,播放已完成在iOS 10+?

c3frrgcw  于 2023-10-15  发布在  Swift
关注(0)|答案(2)|浏览(94)

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

MPNowPlayingInfoCenter.default().nowPlayingInfo = nil

播放器仍在锁定屏幕上,但艺术家/歌曲字段为空

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 = [:]
}
anauzrmj

anauzrmj1#

TL;DR

Github上的例子:https://github.com/JakubMazur/SO52243428
您不应该将nil分配给此nowPlayingInfo
要实现这一点,您应该做的是:
1.停止播放(不需要,但清理你创建的内容很好)
1.将会话设置为非活动状态
1.清除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 = [:]

它的行为是这样的:

编辑:

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

hfwmuf9z

hfwmuf9z2#

对我来说是工作。

func setupNowPlaying() {
    var nowPlayingInfo = [String : Any]()
    nowPlayingInfo[MPMediaItemPropertyTitle] = "my video"
    if let image = UIImage(named: "video image") {
        nowPlayingInfo[MPMediaItemPropertyArtwork] =
            MPMediaItemArtwork(boundsSize: image.size) { size in
                return image
        }
    }
    let playerItem = self.player?.currentItem
    
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem?.currentTime().seconds
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem?.asset.duration.seconds
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = self.player?.rate
 
    
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
    
    UIApplication.shared.beginReceivingRemoteControlEvents()
    
}

func closeVideo() {
    self.player?.pause()
    
    let sessionAV = AVAudioSession.sharedInstance()
    try? sessionAV.setActive(false, options: AVAudioSession.SetActiveOptions.notifyOthersOnDeactivation)
    
    
    MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
    
    UIApplication.shared.endReceivingRemoteControlEvents()
}

相关问题