【问题标题】:background audio working on iOS simulator but not device背景音频在 iOS 模拟器上工作,但在设备上不工作
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 2012-08-19
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多