ubuntu下pyttsx3代码

参考:
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)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值