"""Maidservant""" import time import os import pyaudio import wave import speech_recognition as sr from aip import AipSpeech import requests import json from playsound import playsound from wxpy import Bot #百度语音识别API(自己申请,然后都换成自己的) APP_ID = ‘XXXXXXX‘#百度语音识别id API_KEY = ‘xxxxxxxxxx‘#语音识别key SECRET_KEY = ‘xxxxxxxxxxxxxxxx‘#SECRET_KEY client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 图灵API TURING_KEY = "xxxxxxxxxx"#图灵Key URL = "http://openapi.tuling123.com/openapi/api/v2" HEADERS = {‘Content-Type‘: ‘application/json;charset=UTF-8‘} bot=Bot(cache_path=True) # 使用SpeechRecogenition转成录音格式 def rec(rate=16000): r = sr.Recognizer() with sr.Microphone(sample_rate=rate) as source: print("Please start talking") audio = r.listen(source) with open("voices/recording.wav", "wb") as f: f.write(audio.get_wav_data()) # 使用百度语音转文字技术 def listen(): with open(‘voices/recording.wav‘, ‘rb‘) as f: audio_data = f.read() result = client.asr(audio_data, ‘wav‘, 16000, { ‘dev_pid‘: 1536, }) result_text = result["result"][0] print("You said: " + result_text) return result_text # 图灵对话 def robot(text=""): data = { "reqType": 0, "perception": { "inputText": { "text": "" }, "selfInfo": { "location": { "city": "西安", "street": "鱼化寨街" } } }, "userInfo": { "apiKey": TURING_KEY, "userId": "starky" } } data["perception"]["inputText"]["text"] = text response = requests.request("post", URL, json=data, headers=HEADERS) response_dict = json.loads(response.text) result = response_dict["results"][0]["values"]["text"] print("AI said: " + result) return result # 使用百度文字转语音引擎 def speak(text,filename): result = client.synthesis(text, ‘zh‘, 3, { ‘spd‘: 4, ‘vol‘: 5, ‘per‘: 4, }) with open(filename, ‘wb‘) as f: f.write(result) # 播放MP3文件 def play(filename): playsound(filename) filenumber = 0 final_text = "" while True: rec() request = listen() my_friend = bot.friends().search(u‘XXX‘)[0] #微信昵称 my_friend.send(request) response = robot(request) audiofile = f"voices/audio0{filenumber}.mp3" speak(response,audiofile) play(audiofile) final_text = final_text + "You said: " + str(request) +"\r\n" final_text = final_text + "MaidServant said: " + str(response) +"\r\n" my_friend1=bot.friends().search(u‘XXXXX‘)[0]#微信昵称 my_friend1.send(response) filenumber = filenumber + 1 if request.__contains__("结束"): break with open(f‘HouseGirl.txt‘, ‘wb‘) as txt_f: txt_f.write(final_text.encode(‘utf-8‘))