Я использую AVPlayer для воспроизведения звука. Я настраиваю удаленное управление на viewDidLoad
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.isEnabled = true
commandCenter.stopCommand.isEnabled = true
commandCenter.togglePlayPauseCommand.isEnabled = true
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.isEnabled = true
if #available(iOS 13, *){
// Add handler for Play Command
commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.isReadyToPlay, let player = self.audioPlayer, player.timeControlStatus != .playing {
self.playCC()
return .success
}
return .commandFailed
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.isReadyToPlay, let player = self.audioPlayer, player.timeControlStatus == .playing {
self.pauseCC()
return .success
}
return .commandFailed
}
commandCenter.stopCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.pauseCC()
return MPRemoteCommandHandlerStatus.success
}
commandCenter.togglePlayPauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.playPauseCC()
return MPRemoteCommandHandlerStatus.success
}
commandCenter.nextTrackCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.nextCC()
return MPRemoteCommandHandlerStatus.success
}
commandCenter.previousTrackCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
self.prevCC()
return MPRemoteCommandHandlerStatus.success
}
} else {
commandCenter.pauseCommand.addTarget(self, action: #selector(self.pauseCC))
commandCenter.playCommand.addTarget(self, action: #selector(self.playCC))
commandCenter.stopCommand.addTarget(self, action: #selector(self.pauseCC))
commandCenter.togglePlayPauseCommand.addTarget(self, action: #selector(self.playPauseCC))
commandCenter.nextTrackCommand.addTarget(self, action: #selector(self.nextCC))
commandCenter.previousTrackCommand.addTarget(self, action: #selector(self.prevCC))
}
В ViewWillDisappear я вызываю
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.removeTarget(self)
commandCenter.pauseCommand.removeTarget(self)
commandCenter.previousTrackCommand.removeTarget(self)
commandCenter.nextTrackCommand.removeTarget(self)
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.removeTarget(self)
}
, к сожалению, бывают случаи, когда я проигрываю звук с пульта дистанционного управления (приложение находится в фон), и звук воспроизводится дважды. Что я делаю не так?