使用pyttsx的python包,你可以將文本轉換為語音。
安裝命令
pip install pyttsx3 -i https://pypi.tuna.tsinghua.edu.cn/simple
運行一個簡單的語音 ‘大家好'。
1
2
3
4
|
import pyttsx3 as pyttsx engine = pyttsx.init() #初始化 engine.say( '大家好' ) engine.runAndWait() |
另一種文本轉語音方法。
1
2
3
4
|
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完成文本轉換語言
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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將語音轉換成文本
首先安裝兩個工具包
1
2
|
pip install PocketSphinx pip install SpeechRecognition |
然后下載cmusphinx-zh-cn-5.2.tar中文識別的放到anaconda的python虛擬環境的目錄下
Lib\site-packages\speech_recognition\pocketsphinx-data路徑下
解壓文件重命名為zh-CN
1
2
3
4
5
6
7
8
9
10
11
|
#將語音轉換成文本 使用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) |
到此這篇關于python語音識別的文章就介紹到這了,更多相關python語音識別內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_34904125/article/details/120809485