当应用程序已经在后台时如何开始播放音乐?
我正在编写一个应用程序,需要播放声音作为对用户位置变化的反应。
当应用程序在主要焦点(而不是在后台)运行时,一切正常,并且使用 AVAudioPlayer 可以正确播放声音。
如果我使应用程序进入后台(通过按主页按钮),声音会继续播放(我已更改 info.plist 文件并使用 [[AVAudioSession共享实例] setCategory:AVAudioSessionCategoryPlayback错误:nil]; 使这成为可能)。
我的问题是,如果当应用程序已经在后台时发生 GPS 事件,则永远不会播放声音(即使应用程序返回到主焦点时也不会播放),尽管我可以在控制台中看到 GPS 事件已被捕获,当我使用断点进行调试时,我可以看到应该播放音乐的代码已执行,但音乐仍然没有播放。
我的问题是:当应用程序不在主要焦点(在后台)时,如何使应用程序开始播放声音?
I am writing an app that needs to play a sound as a reaction to a change in the users location.
when the app is running in the main focus (not in the background) everything works well and the sound is played correctly using AVAudioPlayer.
if i make the app go to the background (by pressing the home button) the sound keeps playing (i have changed the info.plist file and used
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
to make this possible).
my problem is that if the GPS event occurs when the app is already in the background the sound is never played (not even when the app is returned to the main focus) all though i can see in the console that the GPS event was captured, and when i debug using breakpoints i can see that the code that is supposed to play the music is preformed, but still the music is not played.
my question is: how can I make the app start playing a sound when it is not in the main focus (its in the background)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你不能这样做,因为激活应用程序的唯一方法是通过通知,而这些是按时间安排的,而不是由操作触发。也许,有一种使用后台线程的方法,但无论如何都会被苹果拒绝,所以没有必要坚持下去。
哈特哈,
马库斯
I think you cannot do this, as the only way to activate you app is via a notification, and those are sheduled by time, not triggered by action. Maybe, there's a way using a background-thread, but that would be rejected by Apple anyway, so there's no sense in persuing.
HTH,
Marcus
我认为您只需将您的应用程序声明为音频应用程序即可。您可以通过在 info.plist 文件中添加带有音频值的 UIBackgroundMode 键来实现此目的。
I think you just need to declare your application as audio application. You can do this by adding UIBackgroundMode key with value audio in your info.plist file.