如何在后台播放音频文件?
如何在后台播放音频文件?
这是我的代码:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
alarmAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
if(audioError != nil) {
NSLog(@"An audio error occurred: \"%@\"", audioError);
}
else {
[alarmAudioPlayer setNumberOfLoops: -1];
[alarmAudioPlayer play];
}
}
但是当我执行多任务时它不会继续播放,但当我执行多任务返回应用程序时它会恢复。
注意:我知道这是一个旧问题的重复,但该答案对我不起作用。
How can I play an audio file in the background?
This is my code:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"Alarm" ofType:@"caf"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
alarmAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
if(audioError != nil) {
NSLog(@"An audio error occurred: \"%@\"", audioError);
}
else {
[alarmAudioPlayer setNumberOfLoops: -1];
[alarmAudioPlayer play];
}
}
But it doesn't continue playing when I multitask, but then resumes when I multitask back to the app.
Note: I know this is a duplicate of a old question but that answer didn't work for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您已将应用程序设置为使用后台音频 API。在应用的
Info.plist
中添加此条目:Make sure you have set your application to utilize the background audio API. Add this entry in your app's
Info.plist
: