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



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

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])