首页 文章

iPhone AudioServicesPlaySystemSound:通过耳机路由?

提问于
浏览
4

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

        }
   }

我知道我必须遗漏一些东西,一些设置会做到这一点 . 有任何想法吗?

1 回答

  • 4

    谢谢@Till指着我relevant portion of the docs . 对于有此问题的其他人,解决方案是明确地将会话类别设置为环境声音 . 此代码剪切自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);
    
            }
        }
    

    这方便地解决了我的问题!我唯一担心的是每次播放声音都明确地设置它可能会过度 . 任何人都知道一种更好,更安全的方式来设置并忘记它吗?否则,这很愉快 .

相关问题