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

How to play AVSpeechSynthesizer through call receiver speaker?

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

AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:_strTextCheck];
    AVSpeechSynthesizer *syn = [[AVSpeechSynthesizer alloc] init];
    [syn speakUtterance:utterance];

我知道了,但这不适用于 AVSpeechSynthesizer:

[AVAudioSession  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];

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

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

[[AVAudioSession sharedInstance] 
     overrideOutputAudioPort:AVAudioSessionPortOverrideNone
                       error:nil];

这是一个完整的例子。您还需要设置 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];
}

这对我有用:

try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker])