功能简介:
利用网页实现录音并给予websocket发送给服务端进行录音文件的识别文字,再通过引用图灵机器人技术,对语音文字内容进行相应的回复,之后对回复信息再转换成音频文件发送给前端播放,从而实现网页版本的只能问答机器人功能
服务端
基于Flask搭建我们的服务端,并采用websocket建立服务端与客户端的交互
from flask import Flask,request,render_template from geventwebsocket.websocket import WebSocket from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import os import uuid import baidu_ai app=Flask(__name__) # @app.route('/',strict_slashes=False) # def home(): # return render_template('listen_say.html') @app.route('/toy') def toy(): user_socket = request.environ.get("wsgi.websocket") #type:WebSocket while True: msg=user_socket.receive() #利用uuid给文件命名 并用到python3.6新语法格式化字符串 wav_file = f"{uuid.uuid4()}.wav" #拼接文件路径 放到templates下面存放 wav_file_path = os.path.join('templates',wav_file) #判断文件类型,如果是音频数据则执行写入等一系列操作 if type(msg) == bytearray: with open(wav_file_path,'wb')as f: f.write(msg) #将音频数据转换成正常文本数据 text = baidu_ai.audio2text(wav_file_path) #对此文本数据进行识别并回复相应内容 answer=baidu_ai.faq(text,'xxx') #再将文本数据转换成音频文件 file_name=baidu_ai.text2audio(answer) #将转换过后的音频文件路径发给客户端 user_socket.send(file_name) if __name__ == '__main__': http_server = WSGIServer(('127.0.0.1',8000),app,handler_class=WebSocketHandler) http_server.serve_forever()
由于我们需要将前端发送给我们的音频文件先解析成文本,只能才能根据文本内容来让图灵机器人帮我们做出对应的答复,之后又要将答复的内容转换成音频文件传输给前端完成真正意义上的沟通交流,所以需要用到百度的文字转语音,语音转文字两个功能,加上图灵机器人api的调用
from aip import AipSpeech import os import uuid from aip import AipNlp import to_tuling """ 你的 APPID AK SK """ APP_ID = '11710179' API_KEY = 'Pmnoe7g14eryGgkDfMQAqakk' SECRET_KEY = '2sTfYI0GRhdCKazWQR9L1AqfGwt7FNAc ' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) baidu_nlp = AipNlp(APP_ID, API_KEY, SECRET_KEY) def audio2text(file_name): # 将wav wma mp3 等音频文件转换为 pcm 无压缩音频文件 cmd_str = "ffmpeg -y -i %s -acodec pcm_s16le -f s16le -ac 1 -ar 16000 %s.pcm" % (file_name, file_name) # 调用操作自动执行上述命令完成转换 os.system(cmd_str) # 读取音频文件数据 file_content = "" with open(f"{file_name}.pcm", 'rb')as f: file_content = f.read() # 将音频转换成文本 res = client.asr(file_content,'pcm',16000,{ 'dev_pid':1536 }) # 返回文本数据 return res.get('result')[0] def text2audio(text): # 生成文件名存放转换过的文本文件 mp3_file = f"{uuid.uuid4()}.mp3" mp3_file_path = os.path.join('templates',mp3_file) # 将文本文件识别成音频文件 speech = client.synthesis(text, 'zh', 1, { 'spd': 4, 'vlo': 8, 'pit': 8, 'per': 4 }) # 存放到文件中 with open(mp3_file_path,'wb')as f: f.write(speech) # 将转换成功的音频文件路径发给客户端 return mp3_file def faq(text, user_id): return to_tuling.to_tuling(text, user_id)
图灵机器人接口程序文件(参考图灵提供的API文档即可完成下面代码的书写)
import requests,json #图灵接入接口 tuling_url="http://openapi.tuling123.com/openapi/api/v2" def to_tuling(text,user_id): #按照图灵给我们提供的API文档 传递固定格式的数据 data={ "reqType":0, "perception": { "inputText": { "text": text }, }, "userInfo": { "apiKey": "03f1bb5ce38d40fcb0b19c5544372d6b", "userId": user_id } } #发送json数据给图灵进行匹配测试 res=requests.post(tuling_url,json.dumps(data)) #接收图灵返回的消息 response=json.loads(res.content.decode('utf-8')) response_text=response.get('results')[0].get('values').get('text') return response_text
之后就是我们的前端页面了
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <audio src="" id="player" autoplay="autoplay" controls></audio> <button onclick="start_rec()">开启录音</button> <button onclick="stop_rec()">结束录音</button> </body> <script type="application/javascript" src="Recorder.js"></script> <script type="application/javascript"> //创建websocket连接对象 var ws = new WebSocket('ws://127.0.0.1:8000/toy'); //先声明一个空记录对象 var rec = null; //创建音频对象 var audio_context = new AudioContext(); //兼容浏览器配置 navigator.getUserMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia ); navigator.getUserMedia({audio: true}, create_stream, function (err) { console.log(err) }); //创建录音数据流 function create_stream(stream) { var stream_input = audio_context.createMediaStreamSource(stream); //创建记录录音对象 rec = new Recorder(stream_input); } //开始录音 function start_rec() { rec.record(); } //结束录音 function stop_rec() { rec.stop(); get_audio(); rec.clear(); } //发送录音二进制流数据 function get_audio() { rec.exportWAV(function (wav_file) { ws.send(wav_file); }) } //获取服务端处理好的语音数据 ws.onmessage = function (msg) { //放入音频播放标签内 var player = document.getElementById('player'); player.src = msg.data } </script> </html>
至此就完成了一个能够跟我们进行沟通交流并有一些智能辅助功能的问答机器人雏形