【问题标题】:How to I make my IOS app play music in the background forever?如何让我的 IOS 应用程序永远在后台播放音乐?
【发布时间】:2018-10-26 09:40:08
【问题描述】:

我想编写一个音乐播放器 iOS 应用程序,在后台循环播放音乐。我不想音乐停止。另外,我想运行一个计时器,每隔一段时间执行一次更新,这可能会改变播放的音乐。

  • 当我尝试编写此应用程序时,音乐最终会在一段时间后停止播放。此外,我注意到 iTunes 播放器具有相同的行为。如果我将 iTunes 设置为无限循环播放某首歌曲并让它播放,那么音乐将在几小时内停止播放。

我已经为“音频”后台执行设置了我的应用程序,并且我有这样的代码来开始播放音频:

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with:AVAudioSessionCategoryOptions.mixWithOthers)  
try AVAudioSession.sharedInstance().setActive(true)  
let player = try AVAudioPlayer(contentsOf: sound)  
player.numberOfLoops = -1  
player.prepareToPlay()  
player.delegate = self  
player.play()  

func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {  
  player.play()  
}  

为什么 iOS 会终止我的应用并让它停止播放音乐和运行我的计时器?

【问题讨论】:

  • 你能检查一下你是否遇到了一些错误。阅读Apple documentation 看起来如果另一个活动的音频会话的优先级高于您的(例如,一个电话),并且两个音频会话都不允许混合,那么尝试激活您的音频会话会失败。停用具有正在运行的音频对象的音频会话将停止正在运行的音频对象,停用会话,并返回 AVAudioSessionErrorCodeIsBusy 错误。
  • 您的应用程序中的音频是否有时会暂停或应用程序被杀死?因为 youtube red 具有永远在后台播放的功能,所以我认为我们的应用程序应该可以这样做。但是,是的,正如@todor 所提到的,当另一个音频(如呼叫)出现时,它具有优先权。
  • 我已将代码设置为混合。还。即使手机除了播放音乐什么都不做,iOS 也会终止应用。
  • @gregm 当我们打开我们的应用程序和我们的应用程序也使用 AVAudioPlayer 或 AudioServicesCreateSystemSoundID 时,我们如何允许同时从后台播放任何音乐应用程序中的音乐
  • @gregm 当我打开我的应用程序时,后台应用程序的音乐停止了。以下解决方案对我不起作用 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];伙计们有什么建议吗?当我们不使用任何 AVAudioPlayer 或 AudioServicesCreateSystemSoundID 时,上述解决方案有效

标签: ios iphone background


【解决方案1】:

使用 MPMusicPlayerController.systemMusicPlayer 代替 AVAudioPlayer https://developer.apple.com/documentation/mediaplayer/mpmusicplayercontroller?language=objc

【讨论】:

  • 系统音乐播放器有何不同?
  • AVAudioSession 已附加到您的应用程序。 iOS 不允许后台执行,除非它用于播放音乐。系统音乐播放器由iOS维护
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2014-06-11
相关资源
最近更新 更多