python 调用百度语音api和青云客制作对话机器人

#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('&quot',',')
            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获得的,代码中最后三个注释是要安装的包和软件。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值