Observe iOS system media player and media player remote commands (Volume, Play / Pause, etc.). Use this to control a music player, trigger a shutter button or hijack events from media remotes such as the Ortho Remote.
volumetogglePlayPauseCommandplayCommandpauseCommandstopCommandenableLanguageOptionCommanddisableLanguageOptionCommandchangePlaybackRateCommandchangeRepeatModeCommandchangeShuffleModeCommandnextTrackCommandpreviousTrackCommandskipForwardCommandskipBackwardCommandseekForwardCommandseekBackwardCommandchangePlaybackPositionCommandratingCommandlikeCommanddislikeCommandbookmarkCommand
- Copy
MediaCommandCenter.swiftto your project and ensure it is included inBuild Phases>Compile Sources. - Copy
silence.m4aintoAssets.xcassets. (If you are not playing audio of your own.)
>= iOS 13:
In SceneDelegate, call MediaCommandCenter's prepare and resign methods.
func sceneDidBecomeActive(_ scene: UIScene) {
MediaCommandCenter.prepareToBecomeActive()
}
func sceneWillResignActive(_ scene: UIScene) {
MediaCommandCenter.prepareToResignActive()
}< iOS 13:
In AppDelegate, call MediaCommandCenter's prepare and resign methods.
func applicationDidBecomeActive(_ application: UIApplication) {
MediaCommandCenter.prepareToBecomeActive()
}
func applicationWillResignActive(_ application: UIApplication) {
MediaCommandCenter.prepareToResignActive()
}Add the observing object as an observer and set commands to observe:
MediaCommandCenter.addObserver(self)
MediaCommandCenter.observedCommands = [.volume, .togglePlayPause]Conform to the MediaCommandObserver protocol:
extension MyObject: MediaCommandObserver {
func mediaCommandCenterHandleTogglePlayPause() {
// Handle play/pause toggle
}
func mediaCommandCenterHandleVolumeChanged(_ volume: Double) {
// Handle volume change
}
...
}Remove the observing object on deinit:
deinit {
MediaCommandCenter.removeObserver(self)
}Set the audioPlayer instance in MediaCommandCenter, otherwise the default audio track of 00:00 length silence will play.
While the application is active, it will occupy the system media player with a silent audio track in order to receive system notifications for player control events. MediaCommandCenter listens play/pause/etc. commands from MPRemoteCommandCenter and volume KVO notifications from AVAudioSession.
Note: System media player events will not trigger if the audio player is not initiated.
- Much inspiration from luiswdy/TallyCounter