2016-04-05 61 views
1

我使用下面的代码添加文本到语音功能在我的iOS应用:使用iPhone扬声器AVSpeechSynthesizer

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker) 
try! AVAudioSession.sharedInstance().setActive(true) 
try! AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker) 

let speech : String = "You have the following items in your To-do list: " 
let speechUtterance : AVSpeechUtterance = AVSpeechUtterance(string: speech) 
AVSpeechSynthesizer().speakUtterance(speechUtterance) 

的代码工作完全正常,但声音是从手机的麦克风来了。我想使用扬声器而不是麦克风。我如何实现这一目标?

+0

是“'try!'”有效的Swift语法? –

+0

我认为你对覆盖的理解是背对背的 - 你有没有试过'.None'而不是'.Speaker'? 。 – Grimxn

回答

3

我使用SFSpeechRecognizer进行语音识别,然后为了演讲者发言,您必须执行以下操作。

let audioSession = AVAudioSession.sharedInstance() 
    do { 

    try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) 
    try audioSession.setMode(AVAudioSessionModeSpokenAudio) 
    try audioSession.setActive(true, with: .notifyOthersOnDeactivation) 

        let currentRoute = AVAudioSession.sharedInstance().currentRoute 
         for description in currentRoute.outputs { 
          if description.portType == AVAudioSessionPortHeadphones { 
           try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.none) 
           print("headphone plugged in") 
          } else { 
           print("headphone pulled out") 
           try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker) 
          } 
        } 

} catch { 
     print("audioSession properties weren't set because of an error.") 
} 
+0

你的意思是说话之前,而不是之后?我的意思是你必须在tts之前没有设置音频会话 – user924

+1

是应用程序播放声音之前。在播放声音之前我有语音识别(音频会话有不同的设置),所以我需要在播放声音之前更改音频会话。 –