我使用以下代码在iOS应用中为语音功能添加文字:
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 :(得分: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.")
}