繁体   English   中英

背景音频在iOS模拟器上可运行,但不能在设备上运行

[英]background audio working on iOS simulator but not device

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM