设置标题和图像,以便在后台播放音频

时间:2015-12-04 13:22:02

标签: ios iphone swift avplayer mpnowplayinginfocenter

如何使用AVPlayer

在后台设置正在播放音频的标题和图像

到目前为止我的代码:

  let path: String = String(format: "pathtoaudio")
    let aPlayerItem: AVPlayerItem = AVPlayerItem(URL: NSURL(string: path)!)
    let anAudioStreamer: AVPlayer = AVPlayer(playerItem: aPlayerItem)
    player = anAudioStreamer
    let playerController = AVPlayerViewController()
    playerController.player = player
    self.addChildViewController(playerController)
    self.view.addSubview(playerController.view)
    playerController.view.frame = self.view.frame
    player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: nil)
    let nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!",  MPMediaItemPropertyTitle : "Title!", MPMediaItemPropertyArtwork : MPMediaItemArtwork(image: UIImage(named: "nour.jpg")!)]
    MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = nowPlayingInfo
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

我正在尝试使用MPNowPlayingInfoCenter,但我没有在锁定屏幕上看到这些信息。

1 个答案:

答案 0 :(得分:3)

您的标题和艺术家键看起来是正确的,但要设置相册图片,您需要使用MPMediaItemArtwork对象:

let nowPlayingInfo = [MPMediaItemPropertyArtist : "Artist!",  MPMediaItemPropertyTitle : "Title!", MPMediaItemPropertyArtwork : MPMediaItemArtwork(image: UIImage(...))]
MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = nowPlayingInfo

您可能还需要显式订阅远程控制事件:

UIApplication.sharedApplication().beginReceivingRemoteControlEvents()