语言转声音--简单朗读功能Pyttsx3

上一篇博客介绍了用WeNet实现声音转文字,后来我就想能不能实现文字转语音。这不就是朗读功能么?

有感情的朗读还是很困难的,可能要用到ModelScope上的新模型,但是没有感情的机器音还是很容易的。比如这里使用Pyttsx3实现。

我这里是在Mac上实现,如果在Linux上需要安装ffmpeg和espeak。

安装

pip install pyttsx3

朗读

from math import ceil
import time
import pyttsx3

# 可以不着痕迹的摸鱼
# 上班时间播放小说内容
# 但是,mac可以放,貌似centos不太行
book = open("~/novels/mynovel.txt","r")

txtwhole = book.read()

unit = 500
looptimes = ceil(len(txtwhole) / unit)

engine = pyttsx3.init()

for i in range(looptimes):
    time.sleep(5)
    data = txtwhole[unit*i:unit*(i+1)]
    engine.say(data)
    engine.runAndWait()

每次读500个字,这样就可以上班的时候听小说了!

import pyttsx3
engine = pyttsx3.init() #创建对象
 
"""语速"""
rate = engine.getProperty('rate') #获取当前语速的详细信息
print(rate) #打印当前语速
engine.setProperty('rate',125) #重设语速
 
"""音量"""
volume = engine.getProperty('volume') #获取当前音量(最小为0,最大为1)
print(volume) #打印当前音量
engine.setProperty('volume',1.0) #在0到1之间重设音量
 
"""发音"""
voices = engine.getProperty('voices') #获取当前发音的详细信息
#engine.setProperty('voice',voices[0].id) #更改发音参数
engine.setProperty('voice',voices[1].id) #更改发音参数
 
"""朗读""" #这里朗读的内容没有翻译,因为翻译的话可能运行时会有问题
engine.say('Hello world!')
engine.say('My current speaking rate is '+str(rate))
engine.runAndWait()
engine.stop()
 
"""将音频保存为文件"""
#如果在linux环境中运行,请确保已安装espeak与ffmpeg模块
engine.save_to_file('你好,世界!','test.mp3')
engine.runAndWait()

猜你喜欢

转载自blog.csdn.net/xiaozoom/article/details/128452393