如何在不使用音频会话设置属性的情况下将音频路由到扬声器



由于AudioSessionSetProperty可能会变得deprecated,我正在尝试找到如何使用其他方式将音频路由到speaker的代码示例。

以前我做了以下工作:

-(void)setSpeakerEnabled
{
    debugLog(@"%s",__FUNCTION__);
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (
                         kAudioSessionProperty_OverrideAudioRoute,
                         sizeof (audioRouteOverride),
                         &audioRouteOverride
                         );
}

试图得到相同的结果,但without call AudioSessionSetProperty

在每个版本的 iOS 上,更多的 audioSession 属性都会迁移到 AVFoundation,因此您应该尽可能优先使用这些属性。

由于 iOS 6 kAudioSessionProperty_OverrideAudioRoute在 AVAudioSession 中由该方法表示

- (BOOL)overrideOutputAudioPort:error:

可用值为 AVAudioSessionPortOverrideNoneAVAudioSessionPortOverrideSpeaker

下面是一个完全通过 AVFoundation 配置的示例音频会话:

 - (void)configureAVAudioSession
{
   // Get your app's audioSession singleton object
    AVAudioSession *session = [AVAudioSession sharedInstance];
    // Error handling
    BOOL success;
    NSError *error;
    // set the audioSession category. 
    // Needs to be Record or PlayAndRecord to use audioRouteOverride:  
    success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
                             error:&error];
   if (!success) {
       NSLog(@"AVAudioSession error setting category:%@",error);
   }
    // Set the audioSession override
    success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
                                          error:&error];
    if (!success) {
        NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error);
    }
    // Activate the audio session
    success = [session setActive:YES error:&error];
    if (!success) {
        NSLog(@"AVAudioSession error activating: %@",error);
    }
    else {
         NSLog(@"AudioSession active");
    }
}

更新

从 iOS 7.0 开始,Audio Session Services C API 现已完全弃用,取而代之的是 AVAudioSession。

更新 2

- (BOOL)overrideOutputAudioPort:error:  

是一个方法,而不是一个属性,它设置一个基础的只写 UInt32 值。无法获取当前值,应将该方法视为设置临时状态。如果音频路由更改或中断,该属性将重置为其默认值 ( AVAudioSessionPortOverrideNone )。您可以通过AVAudioSessionDelegate 获取中断通知。

NSError *error;
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker 
                                                   error:&error];    
if(error)
{ 
    NSLog(@"Error: AudioSession cannot use speakers");
}
let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .spokenAudio, options: .defaultToSpeaker)
        try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
    } catch {
        print("error.")
    }  

将此代码粘贴到您的视图加载区域中

Foundry的解决方案以及Mario Diana的博客也允许我升级iOS 7中弃用的音频会话设置代码。我的旧代码基于AudioBufferPlayer by Matthijs Hollemans. 请记住添加 AVFoundation.framework。

相关内容

最新更新