iPhone 音频服务播放系统声音 : route though headphones?

标签 iphone cocoa-touch audio routes audiotoolbox

我在使用 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/

相关文章:

ios - 音频单元 v3 扩展不会出现在主机应用程序中

audio - PIC32MX : SPI1CON. SPIBUSY 位永远不会被清除

python - 音乐Y或音乐N

iphone - 与新应用程序版本同步更改应用程序内购买名称

ios - 保持 iOS 应用程序处于事件状态以使用 MQTT 协议(protocol)

css - iphone屏幕的实际分辨率是多少

ios - UITableViewCell,显示没有滑动的滑动式删除按钮

iphone - 过滤 NSFetchedResultsController 的 nil 值?

iphone - 代码签名错误: Application Identifier 'com.reapptive.Floors2Go' which doesn't match the current setting 'com.reapptive.Floors2Go'

ios - 调整包含 UITextView 的 UICollectionViewCell 以适应 contentSize