根据我们的要求,即使应用程序处于后台,我们也需要播放声音。我们使用[AVAudioPlayer Play]
来播放声音。
如果应用程序在前台,它可以工作。但是如果应用程序在后台并且我们也在音乐播放器中播放歌曲然后控制转到[AVAudioPlayer Play]
语句,则没有任何反应。
我们已经浏览了很多链接,在plist中添加了背景模式,并且还添加了[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
但事情没有成功。
请建议是否有其他选择。
答案 0 :(得分:11)
只需在初始化AVAudioPlayer
实例的位置添加这三行:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mySong" ofType:@"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
// These lines need to be added:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
答案 1 :(得分:3)
要在后台播放音频,只需添加 info.plist 制作一个类似的数组
并将其检入真实设备而非模拟器中
答案 2 :(得分:2)
试试这个,
<强> AppDelegate.m 强>
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}