当前位置:   article > 正文

python文字语音互转_python文字转语音

python文字转语音

目录

pyttsx

SAPI

SpeechLib

PocketSphinx


pyttsx

安装 pyttsx库:pip install pyttsx3  

  1. import pyttsx3 as px3
  2. speak = px3.init() # 初始化语音引擎
  3. rate = speak.getProperty('rate')
  4. print('语速:%s' % rate) # 默认:200
  5. volume = speak.getProperty('volume')
  6. print('音量:%s' % volume) # 默认:1.0
  7. speak.setProperty('rate',100) # 设置语速
  8. speak.setProperty('volume',2.0) # 设置音量
  9. speak.say('合家欢乐啊')
  10. speak.runAndWait()
  11. speak.stop()

SAPI

  1. from win32com.client import Dispatch
  2. text = '大风一日同风起,扶摇直上九万里'
  3. speak = Dispatch('SAPI.SpVoice')
  4. speak.Speak(text)
  5. del speak

SpeechLib

使用SpeechLib,可以从文本文件中获取输入,再将其转换为语音。

安装pip install comtypes

  1. from comtypes.client import CreateObject as ct
  2. from comtypes.gen import SpeechLib
  3. engine = ct('SAPI.SpVoice')
  4. stream = ct('SAPI.SpFileStream')
  5. infile = 'shiju.txt'
  6. outfile = 'luming_audio.wav'
  7. stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
  8. engine.AudioOutputStream = stream
  9. with open(infile, 'r', encoding='utf-8') as f:
  10. theText = f.read()
  11. engine.speak(theText)
  12. stream.close()

PocketSphinx

一个轻量级的语音识别引擎,用于语音转换文本的开源API。

安装库:pip install SpeechRecognition

              pip install pocketsphinx 

  1. import speech_recognition as sr
  2. audio_file = 'luming_audio.wav'
  3. r = sr.Recognizer()
  4. with sr.AudioFile(audio_file) as source:
  5. audio = r.record(source)
  6. try:
  7. # print(r.recognize_sphinx(audio)) # 不指定language参数时,默认识别英文en-US
  8. print(r.recognize_sphinx(audio, language='zh-CN'))
  9. except Exception as e:
  10. print(e)

默认没有汉语包,使用时报错missing PocketSphinx language model parameters directory: "E:\python\Lib\site-packages\speech_recognition\pocketsphinx-data\zh-CN",需要下载:CMU Sphinx - Browse /Acoustic and Language Models at SourceForge.net

下载后的包解压后修改名称为:zh-CN,并将其放在英文包en-US同目录下

 修改zh-CN中的文件名和en-US中的一样

修改后

实现了转换,就是效果不理想

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/354983
推荐阅读
相关标签
  

闽ICP备14008679号