【问题标题】:iPhone AudioServicesPlaySystemSound: route though headphones?iPhone AudioServicesPlaySystemSound:通过耳机路由?
【发布时间】:2011-01-16 15:26:05
【问题描述】:

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

        }
   }

我知道我一定遗漏了一些东西,一些可以做到这一点的设置。有什么想法吗?

【问题讨论】:

标签: iphone cocoa-touch audio routing audiotoolbox


【解决方案1】:

感谢@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);

        }
    }

这很容易解决我的问题!我唯一担心的是每次播放声音时都明确设置它可能会过度。任何人都知道更好,更安全的方法来设置它并忘记它吗?否则,这会很有效。

【讨论】:

  • 谢谢,我无法让声音正常工作,关键是设置类别。
  • AudioSessionSetProperty 在 iOS 7 中已弃用
猜你喜欢
  • 2013-12-06
  • 2012-12-22
  • 1970-01-01
  • 2011-01-23
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多