引入库pyttsx3
pip install pyttsx3=2.7.1
编码
#! /usr/bin/env python
# encoding: utf-8
import pyttsx3
# python3.8
text = '吃了吗?' * 5
def say():
engine = pyttsx3.init()
#调整声音
voices = engine.getProperty('voices')
for v in voices:
print(v)
voice = engine.getProperty('voice')
#0-500
rate = engine.getProperty('rate')
#0-1
volume = engine.getProperty('volume')
print(voice,rate,volume)
#engine.setProperty('rate',100)
engine.setProperty('volume',0.8)
#with open('test.txt', encoding='utf-8') as f_name:
# text = str(f_name.readlines()).replace(r'\n', '')
engine.say(text)
engine.save_to_file(text,r'H:\\temp\\test.mp3')
engine.runAndWait()
if __name__ == "__main__":
say()
pass
语音文件保存
以上版本只能实现文字转为语音播放,需要保存语音可以使用百度的api
安装
pip install baidu-aip
编码
from aip import AipSpeech
def baiduSaveAudio():
#https://ai.baidu.com/ai-doc/SPEECH/Gk4nlz8tc
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis(text, 'zh', 1, {
'vol': 5})
# 识别正确返回语音二进制 错误则返回dict 参照下面错误码
if not isinstance(result, dict):
with open('audio.mp3', 'wb') as f:
f.write(result)