Swift:命令中心不起作用,即使我明确设置了启用按钮?

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

好吧,这里的Apple命令中心有问题,在锁定屏幕上播放背景音频,无法理解原因。似乎很简单,但是我什至没有在命令中心可靠显示剧集信息,绝对不能播放/暂停。

[首先,我开始音频会话:

  do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
                print("Playback OK")
                try AVAudioSession.sharedInstance().setActive(true)
                print("Session is Active")
            } catch {
                print(error)
            }

然后我将命令中心按钮设置为显式启用:

UIApplication.shared.beginReceivingRemoteControlEvents()
        let commandCenter = MPRemoteCommandCenter.shared()


        commandCenter.skipForwardCommand.isEnabled = true
        commandCenter.skipBackwardCommand.isEnabled = true
        commandCenter.nextTrackCommand.isEnabled = true

        commandCenter.togglePlayPauseCommand.isEnabled = true
//        commandCenter.previousTrackCommand.isEnabled = true
//        commandCenter.togglePlayPauseCommand.isEnabled = true

        commandCenter.togglePlayPauseCommand.addTarget(self, action:#selector(togglePlayPause))
//        commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackForward))
//        commandCenter.previousTrackCommand.addTarget(self, action:#selector(nextTrackBack))

        commandCenter.skipForwardCommand.addTarget(self, action:#selector(ffPressed))
        commandCenter.skipBackwardCommand.addTarget(self, action:#selector(rwPressed))

这里是lldb plist键,如果这对音频很重要:

enter image description here

这里怎么了?

audio swift3 avaudiosession mpremotecommandcenter
1个回答
0
投票

也许您的问题很旧,但是有人可能也需要这个,所以这就是我的做法:

Swift 5

let player = AVPlayer()

func commandCenter () {
    let commandCenter = MPRemoteCommandCenter.shared()
    commandCenter.playCommand.addTarget         { (commandEvent) -> MPRemoteCommandHandlerStatus in  self.play();   return .success }
    commandCenter.pauseCommand.addTarget        { (commandEvent) -> MPRemoteCommandHandlerStatus in  self.pause();  return .success }
}

func pause () {
    player.pause ()
    print("paused")
}

func play () {
    player.play()
    print("play")
}

您无需将commandCenter.playCommand启用为true

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