当应用程序在后台时启动 AVAudioPlayer

发布于 2024-12-24 20:20:15 字数 912 浏览 3 评论 0原文

我有一个应用程序,其中配置了 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这似乎是一个显而易见的问题,但您实际上是在现实应用程序中调用 audioPlayer 对象上的 play 方法吗?可能在后台事件处理程序结束时?

[audioPlayer播放];

Seems like an obvious question, but are you actually calling the play method on the audioPlayer object in your real-life application? Probably at the end of background event handler?

i.e. [audioPlayer play];

脱离于你 2024-12-31 20:20:16

据我了解,当应用程序处于后台时,似乎无法开始播放音乐...只能继续在后台播放现有的播放音乐

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文