【发布时间】:2014-02-02 01:44:22
【问题描述】:
我正在编写一个闹钟应用程序,它的工作原理是在后台播放循环静音,直到闹钟响起,此时它会循环播放闹钟声音,直到用户打开应用程序。这是我的 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 的静音开关是关闭的。感谢阅读!
【问题讨论】:
标签: ios iphone objective-c audio background