AVPlayer锁屏控制

时间:2015-11-27 20:36:46

标签: ios swift avplayer

我有一个使用AVPlayer在后台播放音频的应用。我使用MPNowPlayingInfoCenter在锁定屏幕和控制中心上显示歌曲的元数据。一切都很好,除了一件事。

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

我有关于控件如何的截图:

enter image description here

如您所见,我没有前进和上一个按钮。

 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)
        }
    }
}

1 个答案:

答案 0 :(得分:11)

我建议您使用UIEvent来控制锁定屏幕和控制中心上的上一个/下一个/播放/暂停操作,而不是将remoteControlReceivedWithEvent流与MPRemoteCommandCenter一起使用。< / p>

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")

previousTracknextTrackplayAudiopauseAudio都是您班级中控制播放器的所有功能。

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

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