gpt4 book ai didi

ios - AVPlayer 锁屏控件

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:56 24 4
gpt4 key购买 nike

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

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

我有一个控件的屏幕截图:

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

最佳答案

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

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

关于ios - AVPlayer 锁屏控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com