How to play AVSpeechSynthesizer through call receiver speaker?

▼魔方 西西 提交于 2019-12-10 13:25:42

问题


I like to play audio through the call receiver speaker ,currently i am using this for play some text as a audio .

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

I got but this is not for AVSpeechSynthesizer:

[AVAudioSession  overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];

Correctly its working on a normal speaker but i want to make to play through call receiver speaker ,is it possible to do that ?


回答1:


The default behaviour is to play through the call receiver. So if you unset the override - or don't set it in the first place - you should get the behaviour you are after:

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

Here is a full example. You need to also set the audioSession category.

- (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];
}



回答2:


This worked for me:

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


来源:https://stackoverflow.com/questions/38606831/how-to-play-avspeechsynthesizer-through-call-receiver-speaker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!