使用 MPMusicPlayer Controller 时无法修改 MPRemoteCommandCenter 操作



我的应用程序使用MPMusicPlayerController.systemMusicPlayer()播放音频,效果很好。

用户可以设置自定义currentPlaybackRate。这是意料之中的事。

如果用户按下锁定屏幕上的动作(MPRemoteCommandCenter),则currentPlaybackRate重置为1。这是因为事件直接发送到系统音乐播放器,而不是应用程序控制器。

为了将currentPlaybackRate设置为正确的值,我尝试覆盖MPRemoteCommandCenter事件:

override func viewDidLoad() {
    super.viewDidLoad()
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "playbackStateChanged:", name: MPMusicPlayerControllerPlaybackStateDidChangeNotification, object: player)
    player.beginGeneratingPlaybackNotifications()
    let rcc : MPRemoteCommandCenter = MPRemoteCommandCenter.sharedCommandCenter()
    rcc.playCommand.addTargetWithHandler { (event: MPRemoteCommandEvent!) -> MPRemoteCommandHandlerStatus in
        NSLog("Lock Screen Play Pressed")
        return MPRemoteCommandHandlerStatus.Success
    }
    rcc.togglePlayPauseCommand.addTargetWithHandler { (event: MPRemoteCommandEvent!) -> MPRemoteCommandHandlerStatus in
        NSLog("Lock Screen Play/Pause Pressed")
        return MPRemoteCommandHandlerStatus.Success
    }
}

MPRemoteCommandCenter在使用MPMusicPlayerController时是否应该尊重addTargetWithHandler

如果您并不真正需要MPMusicPlayerController,请尝试使用此解决方案https://github.com/gangverk/GVMusicPlayerController这家伙结合了AVAudioPlayer和MPMusicPlayerController的行为。

但我迫切需要一个答案。因为在我的应用程序中,我真的需要MPMusicPlayerController。

最新更新