Python 实现语音文本互转

文本转语音

使用pyttsx :pip install pyttsx

import pyttsx3 as px3
speaker = px3.init()
speaker.say('你好呀')
speaker.runAndWait()

使用SAPI

from win32com.client import Dispatch
speaker = Dispatch('SAPI.SpVoice')
speaker.Speak('我又回来了')
del speaker

使用SpeechLib

"""使用SpeechLib实现文本转语音"""
from comtypes.client import CreateObject
speak = CreateObject('SAPI.SpVoice')
stream = CreateObject('SAPI.SpFileStream')
from comtypes.gen import SpeechLib
infile = 'demo.txt'          //需要转换的文件
outfile = 'demo_audio.wav'  //输出文件名
stream.open(outfile, SpeechLib.SSFMCreateForWrite)
speak.AudioOutputStream = stream
f = open(infile, 'r', encoding='utf-8')
theText = f.read()
f.close()
speak.speak(theText)
stream.close()

语音转文本

使用PocketSphinx

pip install PocketSphinx
pip install SpeechRecognition

下载PocketSphinx如果有问题,参考:http://t.csdn.cn/TAvmI

"""使用PocketSphinx实现语音转换文字"""
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))  # 默认识别英文en-US
    print(r.recognize_sphinx(audio, language='zh-CN'))
except Exception as e:
    print(e)

中文包下载地址:https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/Mandarin/

下载之后,按照2格式修改文件名

Python 实现语音文本互转_第1张图片

存放路径:

Python39\site-packages\speech_recognition\pocketsphinx-data

Python 实现语音文本互转_第2张图片

 

本文参考:http://t.csdn.cn/80Ose

你可能感兴趣的:(python,开发语言)