在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的要求配置了音频文件的格式和采样率。