【问题标题】:MPMusicPlayerController.play() not working after killing iOS music appMPMusicPlayerController.play() 在杀死 iOS 音乐应用程序后无法正常工作
【发布时间】:2015-08-30 17:03:52
【问题描述】:

我有一个应用程序,可让您在音乐库中搜索歌曲的标题并播放它。我使用此代码播放所选歌曲:

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 错误吗?我不知道发生了什么。

【问题讨论】:

  • 我认为这是一个错误。我在我的应用程序中遇到类似的问题 - 如果我遇到任何解决方法,我会告诉你。
  • 谢谢。这很烦人。

标签: ios swift mpmusicplayercontroller


【解决方案1】:

这是我找到的解决方法。

它的作用是在我尝试开始播放音乐时设置一个计时器。该计时器调用一个函数来测试音乐是否正在播放。如果正在播放音乐,则计时器无效。如果没有,它会重新排队我想要播放的项目(本示例中的项目集合)并尝试再次播放。

我已经从我的应用程序中提取了这段代码并对其进行了抽象,因此它可能无法按原样编译,但希望它能够理解重点。我将向 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()     
    }
}

【讨论】:

  • 当你归档你的雷达时,你能把它添加到openradar,我会欺骗它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多