2016-04-05 44 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

是應用程序播放聲音之前。在播放聲音之前我有語音識別(音頻會話有不同的設置),所以我需要在播放聲音之前更改音頻會話。 –