python 语音识别api google
时间: 2025-03-05 15:39:07 浏览: 10
Google Python 语音识别 API 文档与实例
Google 提供了一个强大的云服务——Speech-to-Text API,用于将音频文件转换成文本。此API支持多种编程语言,其中包括Python[^1]。
为了使用该API,在项目中安装google-cloud-speech
库是必要的:
pip install google-cloud-speech
创建一个简单的脚本来调用这个API并转录音频到文字如下所示:
from google.cloud import speech_v1p1beta1 as speech
import os
def transcribe_audio_file(file_path):
client = speech.SpeechClient()
with open(file_path, 'rb') as audio_file:
byte_content = audio_file.read()
audio = speech.RecognitionAudio(content=byte_content)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="en-US"
)
response = client.recognize(config=config, audio=audio)
for result in response.results:
print(f"Transcript: {result.alternatives[0].transcript}")
if __name__ == "__main__":
file_name = os.path.join(os.getcwd(), "resources", "audio.raw")
transcribe_audio_file(file_name)
上述代码展示了如何读取本地存储的一个线性PCM编码的.raw
格式音频文件,并将其发送给Google Speech-to-Text API进行处理[^2]。
对于更复杂的场景,比如流式传输实时音频数据或自定义模型适应特定领域术语的情况,则可以查阅官方文档获取更多高级特性和配置选项[^3]。
配置环境变量
在运行以上程序之前,请确保已设置好认证所需的环境变量,通常通过命令行执行下述指令完成(假设JSON密钥文件名为keyfile.json
):
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/keyfile.json"
这会告诉客户端库在哪里找到访问云端资源所需的身份验证信息[^4]。
相关推荐


















