Skip to content

Instantly share code, notes, and snippets.

@minsOne
Created March 7, 2015 19:05
Show Gist options
  • Select an option

  • Save minsOne/dd0bcf00721046c26782 to your computer and use it in GitHub Desktop.

Select an option

Save minsOne/dd0bcf00721046c26782 to your computer and use it in GitHub Desktop.
MPMusicPlayerControllerNotification
func initializePlayerNotification() {
myMusicPlayer!.beginGeneratingPlaybackNotifications()
/* Get notified when the state of the playback changes */
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "musicPlayerStateChanged:",
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification,
object: nil)
/* Get notified when the playback moves from one item
to the other. In this recipe, we are only going to allow
our user to pick one music file */
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "nowPlayingItemIsChanged:",
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification,
object: nil)
/* And also get notified when the volume of the
music player is changed */
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "volumeIsChanged:",
name: MPMusicPlayerControllerVolumeDidChangeNotification,
object: nil)
}
func musicPlayerStateChanged(notification: NSNotification){
println("Player State Changed")
/* Let's get the state of the player */
let stateAsObject =
notification.userInfo!["MPMusicPlayerControllerPlaybackStateKey"]
as? NSNumber
if let state = stateAsObject{
/* Make your decision based on the state of the player */
switch MPMusicPlaybackState(rawValue: state.integerValue)!{
case .Stopped:
/* Here the media player has stopped playing the queue. */
println("Stopped")
case .Playing:
/* The media player is playing the queue. Perhaps you
can reduce some processing that your application
that is using to give more processing power
to the media player */
println("Playing")
case .Paused:
/* The media playback is paused here. You might want
to indicate by showing graphics to the user */
println("Paused")
case .Interrupted:
/* An interruption stopped the playback of the media queue */
println("Interrupted")
case .SeekingForward:
/* The user is seeking forward in the queue */
println("Seeking Forward")
case .SeekingBackward:
/* The user is seeking backward in the queue */
println("Seeking Backward")
}
}
}
func nowPlayingItemIsChanged(notification: NSNotification){
println("Playing Item Is Changed")
let key = "MPMusicPlayerControllerNowPlayingItemPersistentIDKey"
let persistentID =
notification.userInfo![key] as? NSNumber
if let id = persistentID?.stringValue {
/* Do something with Persistent ID */
println("Persistent ID = \(id)")
}
}
func volumeIsChanged(notification: NSNotification){
println("Volume Is Changed")
/* The userInfo dictionary of this notification is normally empty */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment