不乱于心,不困于情。
不畏将来,不念过往。如此,安好。

Python文本转化语音

1.用pywin32模块来将文本转化为语音

通过pip install pywin32安装模块,pywin32是个万金油的模块,太多的场景使用到它,但在文本转语音上,它却是个青铜玩家,简单无脑但效果不好。代码示例:

import win32com.client

speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Speak("一天什么时候最安全?中午,因为早晚会出事...")

2.利用pyttsx3来转化

pyttsx3使用pyttsx移植过来的,因为pyttsx不支持python3…针对不同的系统,模块会自动所有系统对应的语音驱动,前提是你的系统存在该驱动…

它依赖pywin32模块,可以说它时针对无脑的pywin32接口,进行了升级的个性化配置。先来看下最简单的使用:

import pyttsx3
engine = pyttsx3.init()
engine.say("明天你好,我叫干不倒!")
engine.runAndWait()

代码初始化模块后,填写你所需转化的文本,之后执行runAndWait方法完成语音转化。再来看看其相关操作:

事件监听

import pyttsx3

def onStart(name):
    print('starting', name)

def onWord(name, location, length):
    print('word', name, location, length)

def onEnd(name, completed):
    print('finishing', name, completed)

engine = pyttsx3.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

中断话语

import pyttsx3
def onWord(name, location, length):
   print 'word', name, location, length
   if location > 10:
      engine.stop()
engine = pyttsx3.init()
engine.connect('started-word', onWord)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

改变声音

import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
   engine.setProperty('voice', voice.id)
   engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

改变语速

import pyttsx3
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate+50)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

改变音量

import pyttsx3
engine = pyttsx3.init()
volume = engine.getProperty('volume')
engine.setProperty('volume', volume-0.25)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

运行驱动程序事件循环

import pyttsx3
engine = pyttsx3.init()
def onStart(name):
   print 'starting', name
def onWord(name, location, length):
   print 'word', name, location, length
def onEnd(name, completed):
   print 'finishing', name, completed
   if name == 'fox':
      engine.say('What a lazy dog!', 'dog')
   elif name == 'dog':
      engine.endLoop()
engine = pyttsx3.init()
engine.connect('started-utterance', onStart)
engine.connect('started-word', onWord)
engine.connect('finished-utterance', onEnd)
engine.say('The quick brown fox jumped over the lazy dog.', 'fox')
engine.startLoop()

使用外部事件循环

import pyttsx3
engine = pyttsx3.init()
engine.say('The quick brown fox jumped over the lazy dog.', 'fox')
engine.startLoop(False)
# engine.iterate() must be called inside externalLoop()
externalLoop()
engine.endLoop()
赞(0) 打赏
未经允许不得转载:seo优化_前端开发_渗透技术 » Python文本转化语音

相关推荐

  • 暂无文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏