![](/img/trans.png)
[英]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.