我在使用 AudioServicesPlaySystemSound 时遇到问题。当输出通过扬声器时,效果很好。然而,当用户插入耳机时,没有输出。有没有一种简单的方法来设置某种监听器,以便在插入耳机时音频自动通过耳机路由,否则通过扬声器路由?
我使用以下方法来播放简短的 AIF 声音样本:
-(void)playAif:(NSString *)filename {
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle]
pathForResource:filename ofType:@"aif"];
if (path) { // test for path, to guard against crashes
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID);
AudioServicesPlaySystemSound (soundID);
}
}
我知道我一定错过了一些东西,一些可以做到这一点的设置。有什么想法吗?
最佳答案
感谢@Till 向我指出 relevant portion of the docs 。对于其他遇到此问题的人,解决方案是显式设置 session 类别,在我的例子中设置为环境声音。此代码摘自 apple's docs :
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; // 1
AudioSessionSetProperty (
kAudioSessionProperty_AudioCategory, // 2
sizeof (sessionCategory), // 3
&sessionCategory // 4
);
所以,我播放音频的方法现在如下所示:
-(void)playAif:(NSString *)filename {
// NSLog(@"play: %@", filename);
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle]
pathForResource:filename ofType:@"aif"];
if (path) { // test for path, to guard against crashes
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; // 1
AudioSessionSetProperty (
kAudioSessionProperty_AudioCategory, // 2
sizeof (sessionCategory), // 3
&sessionCategory // 4
);
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID);
AudioServicesPlaySystemSound (soundID);
}
}
这轻松解决了我的问题!我唯一担心的是,每次播放声音时明确设置它可能会过多。有人知道更好、更安全的方法来设置它并忘记它吗?否则,这会很有效。
关于iPhone 音频服务播放系统声音 : route though headphones?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4706166/