簡體   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