nbpeth nbpeth - 1 year ago 265
Swift Question

How Do I Get Audio Controls on Lock Screen/Control Center from AVAudioPlayer in Swift

New to iOS development, so here goes. I have an app that is playing audio - I'm using

to load single files by name in the app's assets. I don't want to query the user's library, only the files provided. Works great, but, I want the user to be able to pause and adjust volume from the lock screen.

func initAudioPlayer(file:String, type:String){
let path = NSBundle.mainBundle().pathForResource(file, ofType: type)!
let url = NSURL(fileURLWithPath: path)
let audioShouldPlay = audioPlaying()
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url)
audioPlayer.volume = slider.value
audioPlayer.numberOfLoops = -1
// let mpic = MPNowPlayingInfoCenter.defaultCenter()
// mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", MPMediaItemPropertyArtist:"artist"]

My use of
were just experiments from reading other related posts.

Background mode is enabled for audio in my app's plist file

Answer Source

You need to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device.


If you would like to specify custom actions for the MPRemoteCommandCenter:

let commandCenter = MPRemoteCommandCenter.sharedCommandCenter()
commandCenter.nextTrackCommand.enabled = true
commandCenter.nextTrackCommand.addTarget(self, action: "nextTrackCommandSelector")   // and create a method called nextTrackCommandSelector to execute the desired action
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download