我试图让我的程序在后台播放重复的声音。
在 info.plist 中添加(必需的背景模式)属性和(应用播放音频)。
在我的 Storyboard中,应用启动了一个带有根 TableViewController 的 UINarvigation Controller 。在我的根 TableViewController.m 中有#import。
在我的 Root TableViewController 中有一个 NSTimer 属性 my_timer。我在 viewDidLoad 方法中设置如下:
my_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 选择器: @selector(doMyFunction) userInfo:nil repeats:YES];
- 在 doMyFunction 方法中,我有 playSystemSound(1003)。
我的应用程序在前台模式下按预期定期播放声音,但在后台模式下永远不会播放。我无法弄清楚哪里做错了,感谢您的帮助。
最佳答案
playSystemSound 永远不会在后台播放音频。要做到这一点,请在您的主要源代码中调用此函数,只需在 ViewDidLoad 之后:
-(void)createAudioSession
{
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
NSError *myErr;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&myErr];
}
然后
AVAudioPlayer * FXPlayer;
FXPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];
FXPlayer.numberOfLoops = -1; // will loop forever
[FXPlayer play];
关于ios - 音频不在后台播放 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424122/