Set MPNowPlayingInfoCenter duration from AVPlayer?

2019-08-03 07:47发布

问题:

I am trying to set MPNowPlayingInfoCenter, most of the key-value pairs work fine, but there is some kind of issue with playback time

let mpic = MPNowPlayingInfoCenter.defaultCenter()    

mpic.nowPlayingInfo = [
    MPMediaItemPropertyArtwork:albumArtWork,
    MPMediaItemPropertyTitle:titleString,
    MPMediaItemPropertyArtist:artistName,
    MPMediaItemPropertyPlaybackDuration:99,
    MPNowPlayingInfoPropertyElapsedPlaybackTime:String(stringInterpolationSegment:self.myPlayer.currentItem?.currentTime()),
    MPNowPlayingInfoPropertyPlaybackRate:1.0
]

this works and InfoCenter will correctly start counting.

As soon as I try something like

MPMediaItemPropertyPlaybackDuration:String(stringInterpolationSegment:self.myPlayer.currentItem?.duration())

it will fail. Should I be converting CMTime to double? Is there any other property I should access?

回答1:

try this

    let elapsedTime = NSNumber(double : CMTimeGetSeconds(AudioAvPlayer.currentItem!.currentTime()))
    let keys = NSArray(objects:
        MPMediaItemPropertyTitle,
        MPMediaItemPropertyArtist,
        MPMediaItemPropertyPlaybackDuration,
        MPNowPlayingInfoPropertyPlaybackRate,
        MPNowPlayingInfoPropertyElapsedPlaybackTime)
    let values = NSArray (objects:
        m_PlayContent.Title,
        m_PlayContent.Artist,
        m_PlayContent.Duration,
        NSNumber(integer: 1),
        elapsedTime)
    let mediaInfo = NSDictionary(objects: values as [AnyObject], forKeys: keys as! [NSCopying])
    MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = mediaInfo as [NSObject : AnyObject]

duration should be as String / like : 02:24