如何让控制台更新当前播放的歌曲?

时间:2015-08-22 15:26:05

标签: ios swift

我有一个mpmediaitem打印出当前播放的歌曲,艺术家,专辑,但当歌曲改变时,文字不会改变。相反,我希望在歌曲改变时添加另一个标签。我该怎么做呢?

var musicPlayer = MPMusicPlayerController.systemMusicPlayer()
let nowPlaying = MPMusicPlayerController.systemMusicPlayer().nowPlayingItem
let Title = nowPlaying[MPMediaItemPropertyTitle] as? String
let Artist = nowPlaying[MPMediaItemPropertyArtist] as? String
let Album = nowPlaying[MPMediaItemPropertyAlbumTitle] as? String
override func viewDidLoad() {
    super.viewDidLoad()


        NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
    musicPlayer.beginGeneratingPlaybackNotifications()


}

  deinit{
    musicPlayer.endGeneratingPlaybackNotifications()
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func getNowPlayingItem() {
    if let nowPlaying = musicPlayer.nowPlayingItem {
        let title = nowPlaying[MPMediaItemPropertyTitle] as? String
        let artist = nowPlaying[MPMediaItemPropertyArtist] as? String
        let album = nowPlaying[MPMediaItemPropertyAlbumTitle] as? String
        println("Song: \(title)")
        println("Artist: \(artist)")
        println("Album: \(album)")
    }
}

1 个答案:

答案 0 :(得分:0)

使用通知中心观察员监控播放项目的更改。使用Swift命名约定(不要以大写字母开头命名变量)。如果某些数据将被返回为零,则使用非字符串强制转换来避免异常。

<br/>

更新示例