语音对话机器人搭建

基于百度AI和图灵机器人搭建的语音对话机器人

源码:


from aip import AipSpeech
import requests
import json
import speech_recognition as sr
import win32com.client

# 初始化语音
speaker = win32com.client.Dispatch("SAPI.SpVoice")


# 1、语音生成音频文件,录音并以当前时间戳保存到voices文件中
# Use SpeechRecognition to record 使用语音识别录制
def my_record(rate=16000):
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=rate) as source:
        print("please say something")
        audio = r.listen(source)

    with open("voices/myvoices.wav", "wb") as f:
        f.write(audio.get_wav_data())


# 2、音频文件转文字:采用百度的语音识别python-SDK
# 导入我们需要的模块名,然后将音频文件发送给出去,返回文字。
# 百度语音识别API配置参数
APP_ID = '******'
API_KEY = '********'
SECRET_KEY = '************'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
path = 'voices/myvoices.wav'


# 将语音转文本STT
def listen():
    # 读取录音文件
    with open(path, 'rb') as fp:
        voices = fp.read()
    try:
        # 参数dev_pid:1536普通话(支持简单的英文识别)、1537普通话(纯中文识别)、1737英语、1637粤语、1837四川话、1936普通话远场
        result = client.asr(voices, 'wav', 16000, {
    
    'dev_pid': 1537, })
        # result = CLIENT.asr(get_file_content(path), 'wav', 16000, {'lan': 'zh', })
        #print(result)
        #print(result['result'][0])
        #print(result)
        result_text = result["result"][0]
        print("you said: " + result_text)
        return result_text
    except KeyError:
        print("KeyError")
        speaker.Speak("你说啥???风太大我听不见!!!")


# 3、与机器人对话:调用的是图灵机器人
# 图灵机器人的API_KEY、API_URL
turing_api_key = "********"
api_url = "http://openapi.tuling123.com/openapi/api/v2"  # 图灵机器人api网址
headers = {
    
    'Content-Type': 'application/json;charset=UTF-8'}


# 图灵机器人回复
def Turing(text_words=""):
    req = {
    
    
        "reqType": 0,
        "perception": {
    
    
            "inputText": {
    
    
                "text": text_words
            },

            "selfInfo": {
    
    
                "location": {
    
    
                    "city": "天津",
                    "province": "天津",
                    "street": "蓟县"
                }
            }
        },
        "userInfo": {
    
    
            "apiKey": turing_api_key,  # 你的图灵机器人apiKey
            "userId": "Tuesday"  # 用户唯一标识(随便填, 非密钥)
        }
    }

    req["perception"]["inputText"]["text"] = text_words
    response = requests.request("post", api_url, json=req, headers=headers)
    response_dict = json.loads(response.text)

    result = response_dict["results"][0]["values"]["text"]
    print("AI Robot said: " + result)
    return result


# 语音合成,输出机器人的回答
while True:
    my_record()
    request = listen()
    response = Turing(request)
    speaker.Speak(response)

大体思路就是通过百度API把音频转化为文字,然后通过图灵机器人得到回复,TTS将文本转成音频播放出来。

做完觉得其实以前觉得很厉害的东西其实也没有那么难搞,不过就是掉几根头发熬几个晚上而已。

大头是下包包,搞了好久,在这里谢谢我的好兄弟张玥熙,帮我解决了很大的难题,我祝她想吃鸡就吃鸡,上王者轻而易举,斗地主3456必有7。

总的来说这次没什么参与感,仅仅就是下了几个库调了几个接口而已,不过还是很开心啦,毕竟是第一次做出自己的机器人嘤嘤嘤。

最后是我与鸡肋机器人对话的视频,看一乐儿得了

《我与大鹅》标题有点短,详细的标题更容易吸引用户增加曝光

猜你喜欢

转载自blog.csdn.net/m0_46330606/article/details/112261104