python文字语音互转

目录

pyttsx

SAPI

SpeechLib

PocketSphinx


pyttsx

安装 pyttsx库:pip install pyttsx3  

import pyttsx3 as px3

speak = px3.init()  # 初始化语音引擎
rate = speak.getProperty('rate')
print('语速:%s' % rate)  # 默认:200
volume = speak.getProperty('volume')
print('音量:%s' % volume)  # 默认:1.0
speak.setProperty('rate',100)  # 设置语速
speak.setProperty('volume',2.0)  # 设置音量
speak.say('合家欢乐啊')
speak.runAndWait()
speak.stop()

SAPI

from win32com.client import Dispatch

text = '大风一日同风起,扶摇直上九万里'
speak = Dispatch('SAPI.SpVoice')
speak.Speak(text)
del speak

SpeechLib

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

安装pip install comtypes

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

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

infile = 'shiju.txt'
outfile = 'luming_audio.wav'
stream.Open(outfile, SpeechLib.SSFMCreateForWrite)
engine.AudioOutputStream = stream
with open(infile, 'r', encoding='utf-8') as f:
    theText = f.read()
engine.speak(theText)
stream.close()

PocketSphinx

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

安装库:pip install SpeechRecognition

              pip install pocketsphinx 

import speech_recognition as sr

audio_file = 'luming_audio.wav'
r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
    audio = r.record(source)
try:
    # print(r.recognize_sphinx(audio))  # 不指定language参数时,默认识别英文en-US 
    print(r.recognize_sphinx(audio, language='zh-CN'))
except Exception as e:
    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中的一样

修改后

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

  • 0
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值