I want to build a radio app and so I would like to use the stop button instead of the pause button in the control center like Apple Radio does in the native music app :
Here is what I did in my RadioPlayer class :
private var shoutcastStream = NSURL(string: "http://shoutcast.com:PORT/;stream.mp3")
var playerItem:AVPlayerItem?
var player:AVPlayer?
let commandCenter = MPRemoteCommandCenter.sharedCommandCenter()
override init() {
super.init()
do {
// Allow background audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ as NSError {
}
// Disable Next, Prev and Pause
commandCenter.pauseCommand.enabled = false
commandCenter.nextTrackCommand.enabled = false
commandCenter.previousTrackCommand.enabled = false
// Enable Play
commandCenter.playCommand.enabled = true
commandCenter.playCommand.addTarget(self, action: #selector(RadioPlayer.play))
// Enable Stop
commandCenter.stopCommand.enabled = true
commandCenter.stopCommand.addTarget(self, action: #selector(RadioPlayer.stop))
} catch _ as NSError {
}
}
It's now working fine but the stop button isn't showing. Instead, I have the Pause button, which doesn't make sense for a radio player haha.
Note that in the above case, even if the control center is showing the pause button, nothing happens when pause button is pressed, because no target is attached to it (I attached it to the stopCommand
).
So the question is: how to use that Stop button? Thank you.