多语言展示
当前在线:615今日阅读:113今日分享:31

python 智能对话

pyaudio录音\baidu语言识别\图灵智能\baidu语言合成\mp3播放
工具/原料
1

电脑

方法/步骤
1

下载python运行环境,这里是使用的2.7,可网络搜索python2.7下载安装

2

python 代码from aip import AipSpeechimport urllib  import jsonimport requestsimport mp3playimport pyaudioimport waveimport time APP_ID = ''API_KEY = ''SECRET_KEY = ''aipSpeech = AipSpeech(APP_ID, API_KEY, SECRET_KEY) key = ''  api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='url = "http://www.tuling123.com/openapi/api"user_id = 'tosobright' def get_file_content(filePath):    with open(filePath, 'rb') as fp:        return fp.read() def getHtml(url):      page = urllib.urlopen(url)      html = page.read()      return html def getHtml2(data):    body = {'key': key, 'info': data.encode('utf8'), 'userid': user_id}    r = requests.post(url, data=body)    return r.text while 1:    print("------Start-------")    p = pyaudio.PyAudio()    RECORD_SECONDS = 5    stream = p.open(format=8,channels=1,rate=16000,input=True,frames_per_buffer=1024)    print("* recording")    frames = []    for i in range(0, int(16000 / 1024 * RECORD_SECONDS)):        data = stream.read(1024)        frames.append(data)    print("* done recording")    stream.stop_stream()    stream.close()    p.terminate()    wf = wave.open("record.pcm", 'wb')    wf.setnchannels(1)    wf.setsampwidth(p.get_sample_size(8))    wf.setframerate(16000)    wf.writeframes(b''.join(frames ))    wf.close()     print('* Get Data From Baidu')    res = aipSpeech.asr(get_file_content('record.pcm'), 'pcm', 16000, {        'lan': 'zh',    })    print res    print res.get('result')[0].encode('cp936')     print('* Get Data From Tuling')    #request = api + res.get('result')[0].encode('cp936')    #print request    #response = getHtml(request)    response = getHtml2(res.get('result')[0])    dic_json = json.loads(response)     print dic_json['text']     print('* Get mp3 From Baidu')    result  = aipSpeech.synthesis(dic_json['text'], 'zh', 1, {        'vol': 5,    })    if not isinstance(result, dict):        with open('au.mp3', 'wb') as f:            f.write(result)     print('* Play mp3')    mp3 = mp3play.load('au.mp3')    mp3.play()    time.sleep(min(30, mp3.seconds()))    mp3.close()

4

注册灵图账号,并获取灵图key,将key值填入代码

5

安装python的依赖库pip install baidu-aippip install requestspip install mp3playpip install pyaudio

6

将第2步的代码保存成ai.py文件,并使用python IDE打开,运行即可

注意事项
1

百度主要用于语音识别和语音合成,灵图用于语义识别

2

灵图的回答是可以人工进行训练的

3

百度的Key和灵图的Key均需使用个人的,代码中不包含

推荐信息