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)
我不是英語原生的詞彙表,非常感謝你在這裏閱讀,如果你明白我在說什麼:]。歡迎任何幫助。