AVPlayer锁屏控制

我有一个应用程序,使用AVPlayer在后台播放audio。 我使用MPNowPlayingInfoCenter在locking屏幕和控制中心上显示歌曲的元数据。 除了一件事以外,一切正常。

锁屏和控制中心的遥控器是播客应用程序的遥控器。 他们没有前进和前一个button。

我有一个如何控制的截图:

在这里输入图像说明

正如你所看到的,我没有前进和前进的button。

override func viewDidLoad() { super.viewDidLoad() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) UIApplication.sharedApplication().beginReceivingRemoteControlEvents() } catch { print(error) } } @IBAction func play(sender: AnyObject) { if isURLAvailable == false { return } if (player!.rate != 0 && player!.error == nil) { player!.pause() } else { player!.play() } updateImage() } func playSong(song: Song) { let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL? let url: NSURL? = documentsDirectoryURL?.URLByAppendingPathComponent(song.fileName) let avItem = AVPlayerItem(URL: url!) player = AVPlayer(playerItem: avItem) player?.play() let artworkProperty = MPMediaItemArtwork(image: song.artwork) MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [MPMediaItemPropertyTitle : lblSongName.text!, MPMediaItemPropertyArtist : song.artist, MPMediaItemPropertyArtwork : artworkProperty, MPNowPlayingInfoPropertyDefaultPlaybackRate : NSNumber(int: 1), MPMediaItemPropertyPlaybackDuration : CMTimeGetSeconds((player!.currentItem?.asset.duration)!)] } override func remoteControlReceivedWithEvent(event: UIEvent?) { print(event!.type) if event!.type == UIEventType.RemoteControl { if event?.subtype == UIEventSubtype.RemoteControlPlay || event?.subtype == UIEventSubtype.RemoteControlPause { play(self) } if event?.subtype == UIEventSubtype.RemoteControlNextTrack { next(self) } if event?.subtype == UIEventSubtype.RemoteControlPreviousTrack { previous(self) } } } 

而不是使用UIEventstream与remoteControlReceivedWithEvent ,我build议您使用MPRemoteCommandCenter来控制locking屏幕和控制中心上的前一个/下一个/播放/暂停动作。

 import MediaPlayer // ... let commandCenter = MPRemoteCommandCenter.sharedCommandCenter() commandCenter.previousTrackCommand.enabled = true; commandCenter.previousTrackCommand.addTarget(self, action: "previousTrack") commandCenter.nextTrackCommand.enabled = true commandCenter.nextTrackCommand.addTarget(self, action: "nextTrack") commandCenter.playCommand.enabled = true commandCenter.playCommand.addTarget(self, action: "playAudio") commandCenter.pauseCommand.enabled = true commandCenter.pauseCommand.addTarget(self, action: "pauseAudio") 

nextTracknextTrackplayAudiopauseAudio都是您class级中控制玩家的所有function。

您可能还需要显式禁用跳过前进和后退命令:

 commandCenter.skipBackwardCommand.enabled = false commandCenter.skipForwardCommand.enabled = false