ios - 后台音频在iOS模拟器上运行,但在设备上不运行

标签 ios iphone objective-c audio background

我正在编写一个闹钟应用程序,该程序的工作原理是在后台播放循环的静音,直到触发警报为止,这时它将循环播放警报声音,直到用户打开该应用程序为止。这是我来自applicationWillResignActive的代码:

UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
}];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"silence" ofType:@".wav"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[player setNumberOfLoops:-1];
alarmTimer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selector(playAlarm) userInfo:nil repeats:NO];
[player prepareToPlay];
[player play];

这是计时器触发的方法:
[player stop];
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@".m4r"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[player setNumberOfLoops:-1];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[player prepareToPlay];
[player play];

当我在模拟器上对其进行测试时,这可以按预期工作。在我的iPhone上,确实调用了计时器的方法,但是音频没有播放。我确实将背景音频添加到我的plist文件中。 iPhone对音频文件名的大小写敏感性不是问题,并且iPhone的静音开关已关闭。谢谢阅读!

最佳答案

解决:显然您不能从后台启动音频。解决方法是使用performSelectorOnMainThread:withObject:waitUntilDone:调用从主线程播放音频的方法。

关于ios - 后台音频在iOS模拟器上运行,但在设备上不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506062/

相关文章:

ios - iOS8.0中UITableViewRowAction如何管理等宽?(更多,删除等操作)

ios - 有没有办法在源代码级别使 CoreML 模型可用于 iOS11+

iphone - 绘制隐藏在半透明 View 下的阴影?

iphone - 基于允许的以下对象的基于算法的对象排序/重新排序

objective-c - 如何实现事件自行生成的基于事件的状态机?

ios - PromiseKit ios Swift 闭包返回类型问题

iphone - 更新项目中的所有 localized.strings

ios - 如何使用自动布局避免 UITextField 和键盘之间的冲突?

ios - 将照片保存到照片库中的文件夹

ios - 从非 UI 类显示 ViewController