突突突突突突

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

准备以下模块中的函数
from aip import AipSpeech
import time
import os
import requests

APP_ID = '15420654'
API_KEY = 'lHlfGfZyH3pDXqKxQnjZtyBl'
SECRET_KEY = 'CLWhR7yoALWV8dFHNWaKGbuyH1cRgQpq'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

def get_file_content(filePath):
# 将文件转换为百度ai接口需要的pcm格式, 使用ffmpeg格式工厂
os.system(f"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm")
with open(f"{filePath}.pcm", 'rb') as fp:
return fp.read()

def audio2text(filePath):
# 识别本地文件
res = client.asr(get_file_content(filePath), 'pcm', 16000, {
'dev_pid':1536,
})

return res.get('result')[0]

def text2audio(text):
# 将文本语音合成音频
filename = f"{time.time()}.mp3"
result = client.synthesis(text, 'zh', 1, {
'vol': 5,
'spd': 3,
'pit': 7,
'per': 4
})

if not isinstance(result, dict):
    with open(filename, 'wb') as f:
        f.write(result)
return filename

def to_tuling(text):
# 向图灵机器人接口发送转换好的文本
url = 'http://openapi.tuling123.com/openapi/api/v2'
data = {
"reqType": 0,
"perception": {
"inputText": {
"text": text
},
},
"userInfo": {
"apiKey": "8931057699874d7994145e6d8b0bab1a",
"userId": "1"
}
}
res = requests.post(url, json=data)
text = res.json().get('results')[0].get('values').get('text')
return text

Flask app############################################################
from flask import Flask, render_template, request, send_file, jsonify
import ai4
from uuid import uuid4

app = Flask(name)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/ai', methods=['POST'])
def ai():
# 接收前端传送的二进制流
audio = request.files.get('record')
filename = f"{uuid4()}.wav"
audio.save(filename)
# 将二进制流音频文件,转换为text
q_text = ai4.audio2text(filename)
# 将q_text发送给图灵机器人进行回答
a_text = ai4.to_tuling(q_text)
# 将a_text答案发送给百度合成音频文件
a_file = ai4.text2audio(a_text)

return jsonify({'filename': a_file})

@app.route('/get_audio/')
def send_audio(filename):
return send_file(filename)

if name == 'main':
app.run(host='0.0.0.0', port=9527, debug=True)

posted on 2019-01-15 19:59  徐建0304  阅读(458)  评论(0编辑  收藏  举报