在iOS模拟器上工作的背景音频,但不是设备

时间:2014-02-02 01:44:22

标签: 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的静音开关是关闭的。谢谢你的阅读!

1 个答案:

答案 0 :(得分:0)

解决了:显然你无法从后台发起音频。解决方法是使用performSelectorOnMainThread:withObject:waitUntilDone:调用从主线程播放音频的方法。