当我的应用程序在后台时,我正在尝试播放声音。我使用AVAudioPlayer
,它在应用处于活动状态时正常工作,但在后台AVAudioPlayer
没有播放任何内容,我不知道该怎么办。
我原以为我可以使用UILocalNotification
,但它会在锁屏中显示并发出警报,我不想要它。
感谢您的回答。我有另一个疑问。如果我创建这个音频,并且我正在播放音乐,那么系统会同时混合两种音乐吗?
如何减少ipod音乐音量,我的应用程序声音正在播放(3秒),并且当它像AppStore中的大多数正在运行的应用程序一样完成时再次增加。 (也在后台)
这是我在AppDelegate中的代码
//Creamos la sesión de audio
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
在我看来,当我想播放声音时:
-(void)avisosound{
// AudioSessionSetActive(YES);
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/sound.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil){
}
else{
[audioPlayer play];
}
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
但是当我播放声音时,ipod音乐会停止。
答案 0 :(得分:4)
您需要在plist文件中进行一些更改。
然后,您需要在AppDelegate中编写以下代码:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
现在,您可以在手机屏幕锁定或您的应用程序处于后台时轻松运行音频。
答案 1 :(得分:1)
以下告诉系统即使iPhone屏幕锁定也会继续播放音频:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
(大多数时候你把它放在didFinishLaunchingWithOptions
。)
要告诉系统在您的应用在后台播放音频时,请添加UIBackgroundModes
并将其设置为您的plist中的audio
。
(任何需要播放音频的前景应用都将优先于这些设置和应用的声音播放。)
要添加“躲避”,要在播放音频时降低其他音频的音量,您需要实现kAudioSessionProperty_OtherMixableAudioShouldDuck。在Audio Session编程指南中查找。
答案 2 :(得分:1)
要在后台播放声音(假设您的应用设置了正确的背景模式),您的应用必须在前台启动声音而不是停止声音。最简单的方法是使用Audio Queue API或RemoteIO Audio Unit。
答案 3 :(得分:0)