当应用程序在后台时启动 AVAudioPlayer
我有一个应用程序,其中配置了 .plist
中的应用程序播放音频
和应用程序提供 IP 语音服务
选项。
应用程序正在接收套接字事件(即使在后台)并根据事件播放声音。当应用程序位于前台时,一切正常。当应用程序在后台时,应用程序被触发,播放器的播放方法被调用,但没有声音。
我已经尝试了许多来自互联网的示例代码,但没有任何效果。我尝试开始在前台播放声音,然后将我的应用程序移到后台,它正在工作。
当应用程序在后台时开始播放声音有什么问题?
这是我的应用程序在后台触发时处理事件的代码:
NSError *error;
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:@"HeadspinLong" withExtension:@"caf"];
if (audioPlayer != nil) return;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
audioPlayer.delegate=self;
if (error) {
NSLog(@"%@", [error localizedDescription]);
}
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive: YES error: &error];
audioSession.delegate=self;
if (error) {
NSLog(@"");
}
I have an application with App plays audio
and App provides Voice over IP services
options configured in the .plist
.
The application is receiving socket events (even in background) and regarding the events, plays sound. When the application is in foreground, all is ok. When the app is in background, the app is triggered, the play method of the player is called, but without sound.
I have tried many sample code from Internet but nothing is working. I have tried to start playing sound in foreground and then move my app in background and it's working.
What is the problem to start playing a sound when the app is in background?
Here's my code handling an event when my app is triggered in background:
NSError *error;
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:@"HeadspinLong" withExtension:@"caf"];
if (audioPlayer != nil) return;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
audioPlayer.delegate=self;
if (error) {
NSLog(@"%@", [error localizedDescription]);
}
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive: YES error: &error];
audioSession.delegate=self;
if (error) {
NSLog(@"");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这似乎是一个显而易见的问题,但您实际上是在现实应用程序中调用
audioPlayer
对象上的play
方法吗?可能在后台事件处理程序结束时?即
[audioPlayer播放];
Seems like an obvious question, but are you actually calling the
play
method on theaudioPlayer
object in your real-life application? Probably at the end of background event handler?i.e.
[audioPlayer play];
据我了解,当应用程序处于后台时,似乎无法开始播放音乐...只能继续在后台播放现有的播放音乐
For my understanding it seems not possible to start playing a music when the app is in background... It is only possible to continue playing an existing played music in background