0
我想使用MPRemoteCommandCenter来控制我的音乐播放器应用程序。现在它可以播放和暂停音乐,但不能播放下一首/上一首歌曲,只有很差的机会才能播放。如何使用线程播放MPRemoteCommandCenter播放的下一首歌曲?
当用户点击MPRemoteCommandCenter中的下一首歌曲按钮时(例如在锁定屏幕中),它会调用startExtendBGJob()函数,然后我要求一个线程来执行更改歌曲作业(我认为bug是在这里,因为我我不完全了解背景工作的解剖结构)。
func startExtendBGJob(taskBlock: @escaping() -> Void) {
registerBackgroundTask()
DispatchQueue.global(qos: .userInitiated).async {
DLog("APP into BG")
DispatchQueue.global(qos: .default).async {
taskBlock()
}
while self.isPlaying == false || self.tmpPlayer == nil { // waiting for new avplayer been created.
Thread.sleep(forTimeInterval: 1)
}
DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + 10) {
self.endBackgroundTask()
}
}
}
func registerBackgroundTask() {
bgIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
[weak self] in
guard let strongSelf = self else { return }
strongSelf.endBackgroundTask()
})
assert(bgIdentifier != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
UIApplication.shared.endBackgroundTask(bgIdentifier)
bgIdentifier = UIBackgroundTaskInvalid
isExtendingBGJob = false
DLog("App exit BG!")
}
在startNextPlay()函数只是寻找下一首歌曲的URL,并prepareToPlay()是用于创建一个新的AVPlayer播放下一首歌曲。
self.tmpPlayer = AVPlayer(url: streamURL)
我不是英语原生的词汇表,非常感谢你在这里阅读,如果你明白我在说什么:]。欢迎任何帮助。