当我启动iPhone游戏时,声音就会立即播放正在播放的背景音乐或播客。我注意到其他游戏允许背景音频继续播放。

这怎么可能?我是否需要在我的应用程序委托(delegate)中覆盖一个方法?

最佳答案

在使用音频播放器之前,请将此行放在application:didFinishLaunchingWithOptions:AppDelegate方法中或一般情况下。

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
根据文档,AVAudioSessionCategoryAmbient类别为

如果还要确保没有错误发生,则必须检查返回值
NSError *error;
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if (!success) {
     //Handle error
     NSLog(@"%@", [error localizedDescription]);
} else {
   // Yay! It worked!
}
最后,不要忘了将AVFoundation框架链接到您的项目并将其导入。
#import <AVFoundation/AVFoundation.h>

10-05 20:23
查看更多