这篇“怎么用Python代码打造一款简单的人工语音对话”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么用Python代码打造一款简单的人工语音对话”文章吧。

gtts

gtts是将文字转化为语音,但是需要在VPN下使用。这个因为要接谷歌服务器。

具体gtts的官方文档:

下面,让我们看一段简单的的代码

fromgttsimportgTTSdefspeak(audioString):print(audioString)tts=gTTS(text=audioString,lang='en')tts.save("audio.mp3")os.system("audio.mp3")speak("HiRunsen,whatcanIdoforyou?")

执行上面的代码,就可以生成一个mp3文件,播放就可以听到了Hi Runsen, what can I do for you?。这个MP3会自动弹出来的。

speech_recognition

speech_recognition用于执行语音识别的库,支持在线和离线的多个引擎和API。

speech_recognition具体官方文档

安装speech_recognition可以会出现错误,对此解决的方法是通过该网址安装对应的whl包

在官方文档中提供了具体的识别来自麦克风的语音输入的代码

下面就是 speech_recognition 用麦克风记录下你的话,这里我使用的是
recognize_google,speech_recognition 提供了很多的类似的接口。

importtimeimportspeech_recognitionassr#录下来你讲的话defrecordAudio():#用麦克风记录下你的话print("开始麦克风记录下你的话")r=sr.Recognizer()withsr.Microphone()assource:audio=r.listen(source)data=""try:data=r.recognize_google(audio)print("Yousaid:"+data)exceptsr.UnknownValueError:print("GoogleSpeechRecognitioncouldnotunderstandaudio")exceptsr.RequestErrorase:print("CouldnotrequestresultsfromGoogleSpeechRecognitionservice;{0}".format(e))returndataif__name__=='__main__':time.sleep(2)whileTrue:data=recordAudio()print(data)

下面是我乱说的英语

对话

上面,我们实现了用麦克风记录下你的话,并且得到了对应的文本,那么下一步就是字符串的文本操作了,比如说how are you,那回答"I am fine”,然后将"I am fine”通过gtts是将文字转化为语音

#@Author:Runsen#-*-coding:UTF-8-*-importspeech_recognitionassrfromtimeimportctimeimporttimeimportosfromgttsimportgTTS#讲出来AI的话defspeak(audioString):print(audioString)tts=gTTS(text=audioString,lang='en')tts.save("audio.mp3")os.system("audio.mp3")#录下来你讲的话defrecordAudio():#用麦克风记录下你的话r=sr.Recognizer()withsr.Microphone()assource:audio=r.listen(source)data=""try:data=r.recognize_google(audio)print("Yousaid:"+data)exceptsr.UnknownValueError:print("GoogleSpeechRecognitioncouldnotunderstandaudio")exceptsr.RequestErrorase:print("CouldnotrequestresultsfromGoogleSpeechRecognitionservice;{0}".format(e))returndata#自带的对话技能(逻辑代码:rules)defjarvis():whileTrue:data=recordAudio()print(data)if"howareyou"indata:speak("Iamfine")if"time"indata:speak(ctime())if"whereis"indata:data=data.split("")location=data[2]speak("HoldonRunsen,Iwillshowyouwhere"+location+"is.")#打开谷歌地址os.system("open-aSafarihttps://www.google.com/maps/place/"+location+"/&")if"bye"indata:speak("byebye")breakif__name__=='__main__':#初始化time.sleep(2)speak("HiRunsen,whatcanIdoforyou?")#跑起jarvis()

以上就是关于“怎么用Python代码打造一款简单的人工语音对话”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。