1

我有一个使用 AVPlayer 播放 mp3 的应用程序,当曲目完成时,我正在努力隐藏远程命令中心。这是设置我的远程命令中心的功能。

我该如何隐藏它?

func setupRemoteCommandCenter() {

    // 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
    }
}
4

1 回答 1

1

您必须从远程控制事件中注销并清除您当前的播放信息MPNowPlayingInfoCenter

UIApplication.shared.endReceivingRemoteControlEvents()        

MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]

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

NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playerItem) 
于 2020-06-25T15:50:20.037 回答