麦克风语音转文本Python案例代码

在Python中,将麦克风捕获的语音转换为文本,通常需要使用语音识别(Speech-to-Text)库。Google的SpeechRecognition库是一个非常流行的选择,因为它支持多种语音识别引擎,包括Google的Web Speech API。

下面是一个使用SpeechRecognition库将麦克风输入转换为文本的简单示例:

首先,你需要安装SpeechRecognition库。如果你还没有安装,可以通过pip进行安装:

 

bash复制代码

pip install SpeechRecognition

然后,你可以使用以下代码来捕获麦克风输入并将其转换为文本:

 

python复制代码

import speech_recognition as sr
def listen_from_microphone_and_transcribe():
# 创建一个Recognizer实例
r = sr.Recognizer()
# 使用麦克风作为音频源
with sr.Microphone() as source:
print("请说话:")
# 读取麦克风输入
audio = r.listen(source)
try:
# 使用Google的Web Speech API进行语音识别
# 注意:Google的Web Speech API已经不再可用,你需要使用其他API,比如Google Cloud Speech-to-Text API
# 或者你可以使用`sr.Recognizer.recognize_google`的替代方案,例如CMU Sphinx或Pocketsphinx
text = r.recognize_google(audio, language='zh-CN') # 假设你希望识别的是中文
print("你说:" + text)
except sr.UnknownValueError:
print("Google Speech Recognition无法理解音频")
except sr.RequestError as e:
print("Google服务出错; {0}".format(e))
# 调用函数
listen_from_microphone_and_transcribe()

请注意,Google的Web Speech API在2019年已经停止了对非Google网站的支持,所以上面的代码段中的r.recognize_google调用现在将不起作用。为了进行语音识别,你需要使用其他的服务,比如Google Cloud Speech-to-Text API,这通常需要你注册Google Cloud并获取API密钥。

以下是使用Google Cloud Speech-to-Text API的示例代码:

 

python复制代码

import speech_recognition as sr
import io
from google.cloud import speech_v1p1beta1 as speech
def listen_from_microphone_and_transcribe_with_google_cloud():
# 创建Recognizer实例
r = sr.Recognizer()
# 使用麦克风作为音频源
with sr.Microphone() as source:
print("请说话:")
audio_data = r.listen(source)
# 将音频数据保存为WAV文件(或者直接处理字节流)
with io.BytesIO() as audio_file:
audio_data.export(audio_file, format="wav")
audio_file.seek(0)
# 设置Google Cloud Speech-to-Text API的凭据
client = speech.SpeechClient()
audio = speech.RecognitionAudio(content=audio_file.read())
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='zh-CN', # 假设你希望识别的是中文
)
# 调用Google Cloud API进行语音识别
response = client.recognize(config=config, audio=audio)
# 输出识别结果
for result in response.results:
print("转录结果: {}".format(result.alternatives[0].transcript))
# 调用函数
listen_from_microphone_and_transcribe_with_google_cloud()

在使用Google Cloud Speech-to-Text API之前,你需要设置Google Cloud项目,并获取相应的API密钥和凭据。此外,还需要安装google-cloud-speech库:

 

bash复制代码

pip install google-cloud-speech

确保你的Google Cloud账户有足够的配额和权限来使用Speech-to-Text API,并且你已经根据API的要求配置了音频文件的格式和采样率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数字化信息化智能化解决方案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值