Python 語音識別 (15)


 

語音識別

語音識別技術,也被稱為自動語音識別,目標是以電腦自動將人類的語音內容轉換為相應的文字和文字轉換為語音。

文本轉換為語音

使用 pyttsx

使用名為 pyttsx python 包,你可以將文本轉換為語音。直接使用 pip 就可以進行安裝

命令如下:

pip install pyttsx3

【示例】使用 pyttsx 實現文本轉換語音

import pyttsx3 as pyttsx engine=pyttsx.init() engine.say('你好 pyttsx') engine.runAndWait()

使用 SAPI

python 中,你也可以使用 SAPI 來做文本到語音的轉換。

【示例】使用 SAPI 實現文本轉換語音

from win32com.client import Dispatch

msg="你好 SAPI"

speaker = Dispatch('SAPI.SpVoice') speaker.Speak(msg) del speaker

使用 SpeechLib

使用 SpeechLib,可以從文本文件中獲取輸入,再將其轉換為語音。先使用 pip 安裝

命令如下:

pip install comtypes

【示例】使用 SpeechLib 實現文本轉換語音

from comtypes.client import CreateObject engine=CreateObject("SAPI.SpVoice") stream=CreateObject('SAPI.SpFileStream') from comtypes.gen import SpeechLib infile='demo.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

PocketSphinx 是一個用於語音轉換文本的開源 API。它是一個輕量級的語音識別引擎,盡管在桌面端也能很好地工作,它還專門為手機和移動設備做過調優。首先使用 pip 命令安裝所需模塊,命令如下:

pip install PocketSphinx pip install SpeechRecognition

【示例】使用 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,language="zh_CN")) print('文本內容:',r.recognize_sphinx(audio))

except Exception as e:

print(e)

注意:

安裝完 speech_recognition 之后是不支持中文的,需要在 Sphinx 語音識別工具包里面 下 載 對 應 的 普 通 話 升 學 和 語 言 模 型 。 下 載 地 址

https://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Mo dels/

將下載好的普通話升學和語言模型放到安裝 speech_recognition 模塊的 pocketsphinx-data 目錄下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM