【问题标题】:Background audio for next track not playing until app moves to foreground (Swift, iOS8.1)直到应用程序移到前台才会播放下一曲目的背景音频(Swift,iOS8.1)
【发布时间】:2015-02-20 10:47:23
【问题描述】:

我正在使用 SoundCloud API 构建流式音频应用程序。有 4 个视图控制器,第 4 个视图控制器是正在播放的音轨 VC - 类似于音乐应用程序上的正在播放场景。

当应用程序处于前台时,一切正常,下一个音轨开始正确播放。当应用程序移到后台时,当前曲目会继续播放,但一旦结束,下一个曲目不会播放,直到我将应用程序带回前台。我检查了一堆现有问题,例如iOS background audio not playing,但没有一个建议的解决方案有效。


我在下面粘贴了用于播放曲目的 playTrack 方法的代码。当我使用调试器时,我可以看到,如果我在下面的闭包内添加断点,则在应用程序进入前台之前不会触发断点。

func playTrack(track: SongSearchResult) {
println("Playing track: \(track.title)")
Logging.sharedInstance.writeData(String(format: "%@:Playing track(%@)", __FUNCTION__, track.title))
audioPlayer?.stop()
if playPauseButton.enabled == false {
  if let request: AnyObject = currentGetRequest {
    SCRequest.cancelRequest(request)
  }
}

currentGetRequest = SCRequest.performMethod(SCRequestMethodGET,
                        onResource: NSURL(string: track.streamURL),
                        usingParameters: nil,
                        withAccount: SCSoundCloud.account(),
                        sendingProgressHandler: nil,
                        responseHandler: {(response, data, error) in

  dispatch_async(dispatch_get_main_queue()) {
    var playerError: NSError? -----------------> BREAKPOINT SET HERE
    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    self.audioPlayer = AVAudioPlayer(data: data, error: &playerError)
    self.audioPlayer?.delegate = self
    self.delegate?.currentTrackChanged(self)
    self.audioPlayer?.prepareToPlay()
    self.audioPlayer?.play()
    self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateTime:"), userInfo: nil, repeats: true)
    self.playPauseButton.enabled = true
    self.currentTimeSlider.enabled = true
  }
})

}


我已经在 Info.plist 文件中设置了 UIBackgroundModes 'audio' 值。有人对我做错了什么有任何建议吗?

谢谢, 阿布舍克。

【问题讨论】:

    标签: ios swift avfoundation soundcloud background-audio


    【解决方案1】:

    好的 - 所以我想我找到了问题所在。看这个链接:objective c - Proper use of beginBackgroundTaskWithExpirationHandler

    因为应用程序注册了背景音频,一旦曲目结束,背景音频就会停止,因此,应用程序(在后台)没有时间完成任何其他任务,即跳到下一个追踪。

    【讨论】:

      【解决方案2】:

      我还要补充一点,您在 dispatch_async() 调用中设置了 AVAudioSession 类别/活动和 .beginReceivingRemoteControlEvents(),这应该在最初设置播放机制时在全局级别上完成(所以可能在你的 viewDidLoad 在你的情况下)。

      我不是 100% 确定,但我认为 dispatch_asyn(dispatch_get_main_queue()) 甚至不会在后台执行?无论哪种方式都没有验证这一点,但是在后台暂停主队列是有意义的。尝试完全删除该调度调用。不熟悉 SCRequest,但如果它类似于 AFNetworking,它可能已经在主队列上调用该完成块。

      【讨论】:

      • 谢谢 - 我会试一试。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多