python - Google 语音转文本 Python 示例代码不起作用
问题描述
以下是我的代码(我对原始示例代码做了一些细微的改动):
import io
import os
# Imports the Google Cloud client library
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
# Instantiates a client
client = speech.SpeechClient()
# The name of the audio file to transcribe
file_name = os.path.join(
os.path.dirname(__file__),
'C:\\Users\\louie\\Desktop',
'TOEFL2.mp3')
# Loads the audio into memory
with io.open(file_name, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='en-US')
# Detects speech in the audio file
response = client.recognize(config, audio)
for result in response.results:
print('Transcript: {}'.format(result.alternatives[0].transcript))
text_file = open("C:\\Users\\louie\\Desktop\\Output.txt", "w")
text_file.write('Transcript: {}'.format(result.alternatives[0].transcript))
text_file.close()
我只能在我的 Windows 提示命令中直接运行此代码,否则系统无法知道 GOOGLE_APPLICATION_CREDENTIALS。但是,当我运行代码时,什么也没发生。我按照所有步骤操作,我可以看到我的控制台上的请求流量发生了变化。但我看不到任何成绩单。有人可以帮我吗?
解决方案
您正在尝试解码编码为 MP3 的 TOEFL2.mp3 文件,同时指定 LINEAR 音频编码
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16
您必须先将 mp3 转换为 wav,请参阅有关 AudioEncoding的信息
推荐阅读
- apache-poi - POI 错误自定义属性当我将属性设置为 MSIP_Label_a7f2ec83-e677-438d-afb7-4c7c0dbc872b_Name: Secret
- maven - 基于配置文件的条件模块
- python - 如何从预测图像中过滤和去除图像中的噪声
- css - Webpack 5 无法编译 boostrap
- python - 检查序列中的元素是否大于前两个元素
- python - pandas:如果值为 NaT,则在数据框中添加行
- math - 逼近未知函数的逆
- jira - 在 Jira 中配置列 - 列管理
- javascript - .catch 控制台错误的生产和开发最佳实践是什么?
- python - 地址更改影响脚本?使用服务器发送电子邮件