使用python怎么制作一个语音聊天机器人?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
import requests import time import pygame from datetime import datetime from aip import AipSpeech from pyaudio import PyAudio,paInt16 import wave import os framerate=8000 NUM_SAMPLES=2000 channels=1 sampwidth=2 TIME=2 def save_wave_file(filename,data): '''save the date to the wavfile''' wf=wave.open(filename,'wb') wf.setnchannels(channels) wf.setsampwidth(sampwidth) wf.setframerate(framerate) wf.writeframes(b"".join(data)) wf.close() def my_record(): pa=PyAudio() stream=pa.open(format = paInt16,channels=1, rate=framerate,input=True, frames_per_buffer=NUM_SAMPLES) my_buf=[] count=0 while count<TIME*6:#控制录音时间 string_audio_data = stream.read(NUM_SAMPLES) my_buf.append(string_audio_data) count+=1 print('.') save_wave_file('0001.wav',my_buf) stream.close() ##def play(): ## wf=wave.open(r"D:/41125.mp3",'rb') ## p=PyAudio() ## stream=p.open(format=p.get_format_from_width(wf.getsampwidth()),channels= ## wf.getnchannels(),rate=wf.getframerate(),output=True) ## while True: ## data=wf.readframes(chunk) ## if data=="":break ## stream.write(data) ## stream.close() ## p.terminate() ## 这里大家需要改成自己的ID和KEY APP_ID = '11****843' API_KEY = '3Mnv***8**88******GbXa' SECRET_KEY = '147***8*88****1227684' aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY) def getText(url): text = requests.post(url).json() return text['text'] ## ##key = '6ddc57c5761a4c62a30ea840e5ae163f' #api = 'http://www.tuling123.com/openapi/api?key=' + key +'&info =' key = '8b005db5f57556fb96dfd98fbccfab84' api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info=' ## while True: ## info = input("我说\n") ## chunk=2014 my_record() print("录音完成") def get_file_content(filePath): with open(filePath,'rb') as fp: return fp.read() a = aipSpeech.asr(get_file_content('0001.wav '),'wav',8000,{}) print(a) b = str(a['result']) info = b url = api + info #print(url) text_01 = getText(url) print("机器人回\n",text_01) now = datetime.now().strftime("%Y-%m-%d_%H_%M_%S") filename_01 = now + ".mp3" result = aipSpeech.synthesis( text_01,'zh',1,{'vol': 5,'per' : 2} ) if not isinstance(result, dict): with open(filename_01, 'wb') as f: f.write(result) print("--------------------------------------") time.sleep(1) pygame.mixer.init() print("语音1") file= filename_01 track = pygame.mixer.music.load(file) pygame.mixer.music.play() time.sleep(15) pygame.mixer.music.stop() pygame.quit()
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。