[英]MPMusicPlayerController play not working with Apple Music
[英]MPMusicPlayerController.play() not working after killing iOS music app
我有一個應用程序,可以讓您在音樂庫中搜索歌曲的標題並播放它。 我使用以下代碼播放所選歌曲:
func playSongByPersistentID(id: Int) { //id is the persistent id of chosen song
let predicate = MPMediaPropertyPredicate(value: id, forProperty: MPMediaItemPropertyPersistentID)
let songQuery = MPMediaQuery()
songQuery.addFilterPredicate(predicate)
if songQuery.items?.count < 1 {
print("Could Not find song") // make alert for this
return
} else {
print("gonna play \(songQuery.items?[0].title)")
}
musicPlayer.prepareToPlay()
musicPlayer.setQueueWithItemCollection(songQuery.collections![0])
musicPlayer.play()
}
上面的函數在tableView(:didSelectRowAtIndexPath)
被調用。 我已確認在選擇歌曲時檢索到了正確的 ID 和歌曲名稱。
這是我的問題。 如果我在關閉 iOS 音樂應用程序后進入我的應用程序並選擇要播放的歌曲,則該歌曲不會播放。 如果我然后選擇不同的歌曲,那不同的歌曲播放沒有問題。 如果我一遍又一遍地選擇同一首歌,它就永遠不會播放。
musicPlayer
是在我的班級中聲明的systemMusicPlayer
。
這是iOS錯誤嗎? 我不知道發生了什么。
這是我找到的解決方法。
一旦我嘗試開始播放音樂,它的作用就是設置一個計時器。 該計時器調用一個函數來測試音樂是否正在播放。 如果正在播放音樂,則計時器無效。 如果沒有,它會重新排隊我想要播放的項目(本示例中的項目集合)並嘗試再次播放。
我已經從我的應用程序中提取了這段代碼並對其進行了抽象,因此它可能無法按原樣編譯,但希望它能夠理解這一點。 我將向 Apple 提交此錯誤(在創建一個小型示例項目之后)並建議您也這樣做。
func playMusic()
{
musicPlayer = MPMusicPlayerController.applicationMusicPlayer()
musicPlayer.setQueueWithItemCollection(MPMediaItemCollection(items: songsForPlayingWithMusicPlayer))
musicPlayer.play()
testForMusicPlayingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: "testForMusicPlaying", userInfo: nil, repeats: false)
}
func testForMusicPlaying()
{
if musicPlayer.playbackState != .Playing
{
testForMusicPlayingTimer.invalidate()
musicPlayer = MPMusicPlayerController.applicationMusicPlayer()
musicPlayer.setQueueWithItemCollection(MPMediaItemCollection(items: songsForPlayingWithMusicPlayer))
musicPlayer.play()
testForMusicPlayingTimer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: "testForMusicPlaying", userInfo: nil, repeats: false)
}
else
{
testForMusicPlayingTimer.invalidate()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.