使用pyttsx的python包,你可以將文本轉換為語音,
安裝命令
pip install pyttsx3 -i https://pypi.tuna.tsinghua.edu.cn/simple
運行一個簡單的語音 ‘大家好’,
import pyttsx3 as pyttsx
engine = pyttsx.init() #初始化
engine.say('大家好')
engine.runAndWait()
另一種文本轉語音方法,
from win32com.client import Dispatch
speaker = Dispatch('SAPI.SpVoice') #創建Dispatch物件
speaker.Speak('大家好') #呼叫Speak方法
del speaker #釋放
這種方法可能會報錯,
ImportError: DLL load failed while importing win32api: 找不到指定的模塊,
網站下載與自己安裝的 “Python" 版本相適應的 "pywin32" 安裝程式,
使用SpeechLib完成文本轉換語言
from comtypes.client import CreateObject
from comtypes.gen import SpeechLib
engine = CreateObject('SAPI.SpVoice') #呼叫方法
stream = CreateObject('SAPI.SpFileStream') #輸出到目標物件的流
infile = '1.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將語音轉換成文本
首先安裝兩個工具包
pip install PocketSphinx
pip install SpeechRecognition
然后下載cmusphinx-zh-cn-5.2.tar中文識別的放到anaconda的python虛擬環境的目錄下
Lib\site-packages\speech_recognition\pocketsphinx-data路徑下
解壓檔案重命名為zh-CN
#將語音轉換成文本 使用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)) #默認識別成英文
print('文本內容:',r.recognize_sphinx(audio,language='zh-CN')) #指定中文
except Exception as e:
print(e)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/321495.html
標籤:其他
上一篇:關于瓦力機器人的設計構想
