我的音频后台模式处于活动状态,我使用此方法播放文件,但是当屏幕锁定时我无法控制它们。
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)
}
}
答案 0 :(得分:2)
对于有相同问题的人,请在问题方法
中调用此方法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
}