Python 实现语音转文本
Python 实现语音转文本
Python可以使用多种方式来实现语音转文本,下面介绍其中两种。
方法一:使用Google Speech API
Google Speech API 是 Google 在 2012 年推出的一个 API,可以用于实现语音转文本。使用 Google Speech API 需要安装 SpeechRecognition 库,可以使用 pip 安装:
pip install SpeechRecognition
安装完成后,可以使用下面的代码实现语音转文本:
import speech_recognition as sr
# 设置音频文件的位置
audio_file = ./audio.wav
# 创建 SpeechRecognition 对象
r = sr.Recognizer()
# 读取音频文件
with sr.AudioFile(audio_file) as source:
audio = r.record(source)
# 识别音频文件
try:
print(r.recognize_google(audio, language=zh-CN))
except sr.UnknownValueError:
raise Google Speech Recognition could not understand audio
except sr.RequestError as e:
raise Could not request results from Google Speech Recognition Service
方法二:使用百度语音识别
除了 Google Speech API 外,还可以使用百度语音识别来实现语音转文本。使用百度语音识别需要安装 Baidu-Aip 库,可以使用 pip 安装:
pip install Baidu-Aip
安装完成后,可以使用下面的代码实现语音转文本:
from aip import AipSpeech
# 设置 APPID、API Key 和 Secret Key
APP_ID = your_app_id
API_KEY = your_api_key
SECRET_KEY = your_secret_key
# 初始化 AipSpeech 对象
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 设置音频文件的位置
audio_file = ./audio.wav
# 读取音频文件
with open(audio_file, rb) as fp:
audio_data = fp.read()
# 识别音频文件
res = client.asr(audio_data, wav, 16000, {
dev_pid: 1536,
})
if res[err_no] == 0:
print(res[result][0])
以上就是使用 Python 实现语音转文本的两种方法。
下一篇:
使用Arduino开发板进行语音识别
