实验环境:已正确安装python3.5
1、安装文本转语音模块
(1)安装pyttsx3模块
该模块应用于文本转语音
(2)安装了pywin32模块
文本转语音模块依赖pywin32模块
2、文本转语音实例
例子:将语音字符串转化为语音播放
完整代码:
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import sys#这两句是添加路径,根据自己模块的安装路径引用
sys.path.append('D:\Anaconda\Lib\site-packages')
import pyttsx3
engine = pyttsx3.init()#初始化对象
engine.say('python 语音speak demo!')
# 注意,没有本句话是没有声音的
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()#say后必须调用该句
3、文本转语音文件
(1)需要安装第三方模块
安装baidu-aip:“pip install baidu-aip”
安装pydub:“pip install pydub”
安装ffmpeg:"pip install ffmpeg"
安装完模块后,需要注册百度云账号。
完整代码:
# -*- coding: utf-8 -*-
#!/usr/bin/python3
from aip import AipSpeech
from pydub import AudioSegment
import time
APP_ID = '你的账号'
API_KEY = '你的_API_KEY'
SECRET_KEY = '你的_Secret_Key'
str1 = input("请输入要转成语音的文字: ")
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis(str1, 'zh', 1, { 'vol': 5,'per':4 })
if not isinstance(result, dict):
with open('temp.mp3', 'wb') as f:
f.write(result)
sound = AudioSegment.from_mp3('temp.mp3')
sound.export(time.strftime("%Y%m%d_%H%M%S", time.localtime())
+".wav", format="wav")