准备以下模块中的函数 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, })
def text2audio(text): # 将文本语音合成音频 filename = f"{time.time()}.mp3" result = client.synthesis(text, 'zh', 1, { 'vol': 5, 'spd': 3, 'pit': 7, 'per': 4 })
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)
@app.route('/get_audio/