python 文字转语音

发布时间 2023-04-15 22:56:37作者: 马昌伟

 

#pyttsx3文字转语音

import pyttsx3
engine2 = pyttsx3.init()
while True:
    content = input('请输入播放内容:')
    engine2.say(content)
    engine2.runAndWait()

pip3 install pyttsx3

#文字转语音

from win32com.client  import Dispatch
msg = '你好'
speaker = Dispatch('SAPI.SpVoice')
speaker.Speak(msg)
del speaker
这个也是没有问题的

 

 

#comtypes模块 文字文件转语音文件(当前仅支持英文)

from comtypes.client import CreateObject
from comtypes.gen import SpeechLib

engine = CreateObject('SAPI.SpVoice')
stream = CreateObject('SAPI.SpFileStream')
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()
可以正常生成录音,我试了试,英文可以,中文也是可以的,

#PocketSphinx模块 SpeechRecognition模块 语音转文字

import speech_recognition as sr
audio_file = 'demo_audio.wav'
r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
    audio = r.record(source)
# try:
    # print('文本内容:',r.recognize_sphinx(audio,language="zh_CN"))
    print('文本内容:',r.recognize_sphinx(audio))

# except Exception as e:
#     print(e)
#https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/ 中文包的网址

pip3 install SpeechRecognition  -i https://mirror.baidu.com/pypi/simple

pip install pocketsphinx  -i https://mirror.baidu.com/pypi/simple

安装上面的包。发现读取语音,转为文字,中文是有问题的。得使用中文包

 

 

添加中文包

https://blog.csdn.net/QFire/article/details/109150312

 

说道这里,大家可能会遇到一些问题,比如碰到这个错误

第一种错误:

Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format

 

这个是啥意思呢,就是你的音频文件必须是wav的格式,而不是你录音之后就直接修改后缀名就可以的,我的是华为手机,录制的音频是ma4,

首先我要转换为wav,我们可以去这个网上在线转换后下载https://www.aconvert.com/cn/audio/m4a-to-mp3/

如果是mp4的,这个地址转换wav格式,https://www.aconvert.com/cn/audio/mp4-to-mp3/

 

明明你这玩意是中文的被翻译成英文的,因为这个库的安装路劲下面只有en-US,当然只能翻译成英文的啦

 

于是我们需要添加一个zh-CN的文件夹,下载对应的中文就可以啦

(1)到对应的python库安装路径下新建zh-CN

(2)https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/下载对应的中文库,下载对应的压缩包后解压

 

 (3)复制以下内容并修改命名

 

 

最后发现为啥还是不行,因为代码初始化的时候默认是英文 en-US,所以这边代码修改一下,即可

 或者修改前面的传参:

 

 

 目录名字没有对应上

 

 不行啊,是可以将语音转为中文了,但是转的不太好

 然后在执行以下你的代码就可以翻译成中文了,感觉python自带的库,最后的结果貌似不太理解,只好在研究研究啦,加油!我感觉可能配置上训练或者学习,可能可以实现比较好的效果

 

 

 

https://blog.csdn.net/QFire/article/details/109150312