2017-06-03 79 views
0

我無法設置MPNowPlayingInfoCenter的currentTime和songLength。這裏是我的代碼:從AVAudioPlayer設置MPNowPlayingInfoCenter currentTime和songLength

func updateNowPlayingCenter (title: String, artist: String, albumArt: AnyObject, currentTime: NSNumber, songLength: NSNumber, PlaybackRate: Double){ 

    var songInfo: Dictionary <NSObject, AnyObject> = [ 

     MPMediaItemPropertyTitle as NSObject: title as AnyObject, 

     MPMediaItemPropertyArtist as NSObject: artist as AnyObject, 

     MPMediaItemPropertyArtwork as NSObject: ???, 

     MPNowPlayingInfoPropertyElapsedPlaybackTime as NSObject: currentTime, 

     MPMediaItemPropertyPlaybackDuration as NSObject: songLength, 

     MPNowPlayingInfoPropertyPlaybackRate as NSObject: PlaybackRate as AnyObject 


    ] 

    MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo as [NSObject : AnyObject] as! [String : Any] 

} 

這裏的地方我將在viewWillAppear中的屬性:

updateNowPlayingCenter(title: titleText[thisSong], artist: authorText[thisSong], albumArt: ??? as AnyObject, currentTime: ???, songLength: ???, PlaybackRate: 1.0) 

我試圖用audioPlayer.currentTime和audioPlayer.duration,但沒有奏效。我該怎麼做呢?此外,我無法弄清楚如何設置MPMediaItemPropertyArtwork的圖像。我的文件中有文件,圖像名稱等於titleText [thisSong]。如果你也可以幫助我,那太棒了!謝謝!

回答

0

蘋果Media Playback Programming Guide提供了答案:

func setupNowPlaying() { 
    // Define Now Playing Info 
    var nowPlayingInfo = [String : Any]() 
    nowPlayingInfo[MPMediaItemPropertyTitle] = "My Movie" 
    if let image = UIImage(named: "lockscreen") { 
     nowPlayingInfo[MPMediaItemPropertyArtwork] = 
      MPMediaItemArtwork(boundsSize: image.size) { size in 
       return image 
     } 
    } 
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds 
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds 
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate 

    // Set the metadata 
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo 
}