001、利用pyttsx3、SAPI、SpeechLib 实现文本转语音

1、使用pyttsx

先安装pyttsx3 : pip3 install pyttsx3

包的使用参考: 在 https://pypi.org/ 搜索pyttsx3

import pyttsx3 as pyttsx

engine = pyttsx.init()
engine.setProperty('rate', 115)  # 设置语音播报速度,一般115比较合适。
engine.setProperty('volume', 1.0)  # 设置音量,level  between 0 and 1,默认是1。

getting details of current voice
voices = engine.getProperty('voices')
changing index, changes voices. o for male。中度的女音,播报中、英文。
engine.setProperty('voice', voices[0].id)
changing index, changes voices. 1 for female。高亮的女音,只播报英文,中文未播报。
engine.setProperty('voice', voices[1].id)

engine.say('测试结束')
engine.say('End of Test')

Saving Voice to a file,On linux make sure that 'espeak' and 'ffmpeg' are installed
engine.save_to_file('测试结束', 'test.mp3')

engine.runAndWait()

以上执行结果:电脑输出语音(测试结束、End of Test)、电脑端保存test.mp3文件。

2、使用SAPI

SAPI是微软Speech API , 是微软公司推出的语音接口,而细心的人会发现从WINXP开始,系统上就已经有语音识别的功能了,可是用武之地相当之少,他并没有给出一些人性化的自定义方案,仅有的语音操控命令显得相当鸡胁。

包的使用参考: 在 https://pypi.org/ 搜索 Speech

from win32com.client import Dispatch

spearker = Dispatch('SAPI.SpVoice')
spearker.Speak('测试结束')
spearker.Speak('End of Test')

以上执行结果:电脑输出语音(测试结束、End of Test)

3、使用SpeechLib

先安装:pip3 install comtypes

comtypes依赖pyttsx3包。( comtypes Required-by: pyttsx3 )

包的使用参考: 在 https://pypi.org/ 搜索 comtypes

您可以从文本文件中获取输入并将其转换为语音。

[En]

You can get input from a text file and convert it to voice.

from comtypes.client import CreateObject

engine = CreateObject('SAPI.SpVoice')
stream = CreateObject('SAPI.SpFileStream')

from comtypes.gen import SpeechLib  # 导这个包必须放在 上面3行代码 后面,否则运行时会报错。

infile = 'demo.txt'
outfile = 'demo_audio.wav'

stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream
读取文本内容
f = open(infile, 'r', encoding='utf-8')
theText = f.read()
f.close()
engine.speak(theText)
stream.close()

运行中可能出现的坑:

1、comtypes下无gen 和 找不到 SpeechLib,如下图:

001、利用pyttsx3、SAPI、SpeechLib 实现文本转语音

001、利用pyttsx3、SAPI、SpeechLib 实现文本转语音

解决方法:

from comtypes.client import CreateObject

engine = CreateObject('SAPI.SpVoice')
stream = CreateObject('SAPI.SpFileStream')

from comtypes.gen import SpeechLib  # 导这个包必须放在 上面3行代码 后面,否则运行时会报错。

Original: https://blog.csdn.net/csdn2780619724/article/details/118143172
Author: QQ_2780619724
Title: 001、利用pyttsx3、SAPI、SpeechLib 实现文本转语音

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/524597/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球