使用 AVAudioPlayer 在锁定屏幕上控制音频

Control audio on lock screen using AVAudioPlayer

我为音频启用了背景模式,我使用这种方法播放文件,但在屏幕锁定时我无法控制它们。

func loadSound(resource: String, soundExtension: String) {
    guard let url = Bundle.main.url(forResource: resource, withExtension: soundExtension) else {
        return
    }

    UIApplication.shared.beginReceivingRemoteControlEvents()

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
    } catch let error {
        print(error.localizedDescription)
    }
}

有同样问题的朋友,在提问方法中调用这个方法

fileprivate let remoteCommandCenter = MPRemoteCommandCenter.shared()

func activateControlCenterCommands() {

    remoteCommandCenter.playCommand.addTarget(self, action: #selector(handlePlayCommandEvent(_:)))
    remoteCommandCenter.pauseCommand.addTarget(self, action: #selector(handlePauseCommandEvent(_:)))

    remoteCommandCenter.playCommand.isEnabled = true
    remoteCommandCenter.pauseCommand.isEnabled = true
}