如何通过呼叫接收器扬声器播放AVSpeechSynthesizer?

Kis*_*mar 6 objective-c ios avspeechsynthesizer

我喜欢通过呼叫接收器扬声器播放音频,目前我正在使用它来播放一些文本作为音频。

AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:_strTextCheck];
    AVSpeechSynthesizer *syn = [[AVSpeechSynthesizer alloc] init];
    [syn speakUtterance:utterance];
Run Code Online (Sandbox Code Playgroud)

我知道了,但这不适合AVSpeechSynthesizer:

[AVAudioSession  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
Run Code Online (Sandbox Code Playgroud)

正确地,它可以在普通扬声器上工作,但是我想通过呼叫接收器扬声器播放,是否可以做到这一点?

fou*_*dry 4

默认行为是通过呼叫接收器播放。因此,如果您取消设置覆盖 - 或者一开始就没有设置它 - 您应该得到您想要的行为:

[[AVAudioSession sharedInstance] 
     overrideOutputAudioPort:AVAudioSessionPortOverrideNone
                       error:nil];
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子。您还需要设置audioSession 类别。

- (void)playVoice {
    [[AVAudioSession sharedInstance] 
             setCategory:AVAudioSessionCategoryPlayAndRecord
                  error:nil];

    //try one or the other but not both...

    //[self playVoiceOnSpeaker:@"test test test"];

    [self playVoiceOnReceiver:@"test test test"];

}

-(void)playVoiceOnSpeaker:(NSString*)str
{
    [[AVAudioSession sharedInstance]  
         overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
                           error:nil];
    [self playVoiceByComputer:str];
}

-(void)playVoiceOnReceiver:(NSString*)str
{
    [[AVAudioSession sharedInstance]
         overrideOutputAudioPort:AVAudioSessionPortOverrideNone
                           error:nil];
    [self playVoiceByComputer:str];
}

-(void)playVoiceByComputer:(NSString*)str
{
    AVSpeechUtterance *utterance = 
          [AVSpeechUtterance speechUtteranceWithString:str];
    AVSpeechSynthesizer *syn = [[AVSpeechSynthesizer alloc] init];
    [syn speakUtterance:utterance];
}
Run Code Online (Sandbox Code Playgroud)