参考:
ubuntu完美安装espeak支持中文和粤语 不再报错:Full dictionary is not installed for ‘zh’
import pyttsx3
import io
import os
import wave
import subprocess
from io import BytesIO
from flask_cors import CORS
from flask import Flask, Response, request
app = Flask(__name__)
#跨域
CORS(app)
@app.route('/ttsx', methods=['POST'])
def tts():
text = request.form['text']
voice = request.form['voice']
rate = request.form['rate']
volume = request.form['volume']
print(text)
print(rate)
print(volume)
#初始化
engine = pyttsx3.init(driverName='espeak')
# engine = pyttsx3.init('espeak')
# voices = engine.getProperty('voices')
# 选择中文语音
# for voice in voices:
# print(voice)
# 设置语音
if int(voice) == 0 :
engine.setProperty('voice', 'zh+f3') # 设置语音(女)
else:
engine.setProperty('voice', 'zh') # 设置语音(男)
engine.setProperty('rate', float(rate)) # 设置语速
engine.setProperty('volume',float(volume)) #设置音量
#写list.txt:先清空
with open("list.txt", "w") as file:
file.write("")
# 每70个字生成一个音频 ,解决长文本发生语音截断问题
text_list = [text[i:i+70] for i in range(0, len(text), 70)]
audio_list = []
for i, sub_text in enumerate(text_list):
filename = f'output_{i}.wav'
#如果没有就先创建
if not os.path.exists(filename):
with open(filename, 'w'):
pass
engine.save_to_file(sub_text, f'output_{i}.wav')
engine.runAndWait()
engine.stop()
#写入list
with open('list.txt', 'a') as f:
f.write(f'file output_{i}.wav\n')
#删除output.wav
if os.path.exists('output.wav'):
os.remove('output.wav')
#合成所有音频
command = "ffmpeg -f concat -i list.txt output.wav"
subprocess.run(command, shell=True)
#获取整合之后的音频流
with open('output.wav', 'rb') as f:
audio = f.read()
#返回前端
return Response(audio, mimetype='audio/wav')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)