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

时间:2016-07-27 07:44:53

标签: ios objective-c avspeechsynthesizer

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

{{1}}

我得到了但这不适用于AVSpeechSynthesizer:

{{1}}

正确地说它正常的扬声器,但我想通过呼叫接收器扬声器播放,是否可以这样做?

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:0)

这对我有用:

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