我正在编写一个闹钟应用程序,该程序的工作原理是在后台播放循环的静音,直到触发警报为止,这时它将循环播放警报声音,直到用户打开该应用程序为止。这是我来自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/