Get current playing song from Spotify iOS app

前端 未结 3 519
慢半拍i
慢半拍i 2020-12-25 12:41

I\'m trying to get info about the current playing song in Spotify iOS app. The scenario is as follows: Open Spotify iOS app, start playing a song. Put the app in background

3条回答
  •  北海茫月
    2020-12-25 13:03

    Here is a solution in Swift 3:

    let player = MPMusicPlayerController.systemMusicPlayer()
    if let mediaItem = player.nowPlayingItem {
        let title: String = mediaItem.value(forProperty: MPMediaItemPropertyTitle) as! String
        let albumTitle: String = mediaItem.value(forProperty: MPMediaItemPropertyAlbumTitle) as! String
        let artist: String = mediaItem.value(forProperty: MPMediaItemPropertyArtist) as! String
    
        print("\(title) on \(albumTitle) by \(artist)")
    }
    

    Note that starting from iOS 10, you must set a description string for NSAppleMusicUsageDescription in the Info.plist in order to get access to the user's music.

    mediaItem will be an instance of MPMediaItem if there is something playing. You can access the media item's attributes using the value(forProperty:) method. This methods takes a property. The properties are defined in the documentation for `MPMediaItem under the heading "General Media Item Property Keys".

提交回复
热议问题