ios 如何在AVPlayer播放完歌曲后隐藏远程指挥中心?

nimxete2  于 2023-10-21  发布在  iOS
关注(0)|答案(1)|浏览(112)

我有一个应用程序播放mp3与AVPlayer和我正在努力隐藏远程指挥中心时,轨道完成。这是设置我的远程指挥中心的函数。
我怎么能隐瞒呢?
public void run(){

// Get the shared MPRemoteCommandCenter
       let commandCenter = MPRemoteCommandCenter.shared()

       // Add handler for Play Command
       commandCenter.playCommand.addTarget { [unowned self] event in
        if self.avPlayer?.rate == 0.0 {
               self.togglePlayPause()
               return .success
           }
           return .commandFailed
       }

       // Add handler for Pause Command
       commandCenter.pauseCommand.addTarget { [unowned self] event in
        if self.avPlayer?.rate == 1.0 {
               self.togglePlayPause()
               return .success
           }
           return .commandFailed
       }

   let skipForwardCommand = commandCenter.skipForwardCommand
   skipForwardCommand.isEnabled = true
   skipForwardCommand.addTarget(handler: skipForward)
   skipForwardCommand.preferredIntervals = [15]

    let skipBackwardCommand = commandCenter.skipBackwardCommand
    skipBackwardCommand.isEnabled = true
    skipBackwardCommand.addTarget(handler: skipForward)
    skipBackwardCommand.preferredIntervals = [15]

    commandCenter.changePlaybackPositionCommand.addTarget { [weak self](remoteEvent) -> MPRemoteCommandHandlerStatus in
        guard let self = self else {return .commandFailed}
        if let player = self.avPlayer {
           let playerRate = player.rate
           if let event = remoteEvent as? MPChangePlaybackPositionCommandEvent {
               player.seek(to: CMTime(seconds: event.positionTime, preferredTimescale: CMTimeScale(1000)), completionHandler: { [weak self](success) in
                   guard let self = self else {return}
                   if success {
                       self.avPlayer?.rate = playerRate
                   }
               })
               return .success
            }
        }
        return .commandFailed
    }
}
lfapxunr

lfapxunr1#

您必须从远程控制事件中取消注册,并从MPNowPlayingInfoCenter中清除当前播放的信息:

UIApplication.shared.endReceivingRemoteControlEvents()        

MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]

您可以使用NotificationCenter观察器观察AvPlayerItem结束:

NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)

相关问题