#coding:utf-8
from aip import AipSpeech
from pyaudio import PyAudio,paInt16
import requests,json,wave,time,pyttsx3
from pydub import AudioSegment
import sys
import os
reload(sys)
sys.setdefaultencoding('utf8')
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
print(client)
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def SaveVoice():
pa=PyAudio()
wf=wave.open(r'T.wav','wb')
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(16000)
stream=pa.open(format=paInt16,channels=wf.getnchannels(),rate=wf.getframerate(),input=True,frames_per_buffer=1024)
buff=[]
start=time.time()
print('用户说:')
while time.time()<start+6:
buff.append(stream.read(wf.getframerate()))
stream.close()
pa.terminate()
wf.writeframes(b''.join(buff))
wf.close()
def RobotSpeakText(usersay="你好"):
url="http://api.qingyunke.com/api.php?key=free&appid=0&msg="+usersay
res = requests.get(url)
return res.json()["content"]
def RobotVoice(robotsay="我没听清,你在说一遍"):
APP_ID1 = ''
API_KEY1 = ''
SECRET_KEY1 = ''
client1 = AipSpeech(APP_ID1, API_KEY1, SECRET_KEY1)
result1 = client1.synthesis(robotsay, 'zh', 1, { 'vol': 5,'per':4 })
if not isinstance(result1, dict):
with open('hello.mp3', 'wb') as f:
f.write(result1)
#print(result1)
sound = AudioSegment.from_mp3('hello.mp3')
sound.export("test.wav", format="wav")
os.system("aplay test.wav")
def main():
while True:
SaveVoice()
result = client.asr(get_file_content('T.wav'), 'wav', 16000, {'dev_pid': 1536})
usersay=result['result'][0]
print(usersay)
robotsay=RobotSpeakText(usersay)
utf8string = robotsay.encode("utf-8")
print(type(utf8string))
utf8string=utf8string.replace('{br}',',')
utf8string=utf8string.replace('"',',')
print('小嘟嘟说:')
print(utf8string)
RobotVoice(utf8string)
if __name__=='__main__':
main()
#pip install baidu-aip
#pip install pydub
#sudo apt-get install ffmpeg
其中APP_ID,API_KEY,SECRET_KEY都是注册百度api获得的,代码中最后三个注释是要安装的包和软件。