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

我喜欢通过电话接收扬声器播放audio,目前我正在使用这个播放一些文本作为audio。

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