2016-07-27 142 views
3

我喜歡通過呼叫接收器揚聲器播放音頻,目前我正在使用它來播放某些文本作爲音頻。如何通過呼叫接收器揚聲器播放AVSpeechSynthesizer?

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

我得到了,但是這不是AVSpeechSynthesizer:

[AVAudioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error]; 

正確的在一個普通的揚聲器工作,但我想打通過電話受話器揚聲器播放,是有可能做到這一點?

回答

3

默認行爲是通過呼叫接收器播放。所以,如果你取消設置覆蓋 - 或不設置它擺在首位 - 你應該得到你之後的行爲:

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

但仍然通過其受話器揚聲器音箱上運行的兄弟http://paste.ofcode.org/uEi8M5FjcGhB97NurcEEsM –

+0

其沒有運行 –

+0

@KishoreKumar - 看到我的更新 - 你需要檢查你的audioSession類別是否正確 – foundry

0

這爲我工作:

try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker]) 
相關問題