首页 > 解决方案 > 获取正在转换为文本的音频文件的持续时间

问题描述

有什么方法可以获取我们正在转换为文本的音频文件的持续时间(以秒为单位)?我们可以在响应正文中看到“totalBilledTime”。我们可以将其视为音频的持续时间吗?用于转换为文本的音频文件的大小或时间(持续时间)是否有任何限制?

标签: pythongoogle-cloud-speech

解决方案


按照快速入门指南,并使用语音识别请求;我创建了一个示例 python 代码:

  1. 确保已将pip install google-cloud-speech其安装在 Cloud Shell 中。请注意,在安装库之前,请确保已准备好 Python 开发环境

  2. 创建将语音转换为文本的 python 代码。

语音转文本.py

# Imports the Google Cloud client library
from google.cloud import speech

# Instantiates a client
client = speech.SpeechClient()

# The name of the audio file to transcribe
gcs_uri = "gs://cloud-samples-data/speech/Google_Gnome.wav"
# Google_Gnome.wav is 55 secs in total

audio = speech.RecognitionAudio(uri=gcs_uri)

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code="en-US",
    enable_word_time_offsets=True,
)

# Detects speech in the audio file
response = client.recognize(config=config, audio=audio)
# By printing the response, this will show the transcribed audio file, by removing the #, this will show the whole transcribed audio file
# print(response)
# last_word will show the last word that was in the audio file
last_word = response.results[-1].alternatives[-1].words[-1]
print("Last Word: ", last_word.word)
print("Last Word End Time: ", last_word.end_time)

通过将值设置enable_word_time_offsetstrue,顶部结果包括单词列表以及这些单词的开始和结束时间偏移(时间戳)。如果为 false,则不返回字级时间偏移信息。默认值为false. 这在RecognitionConfig 文档中有说明。

运行 Speech-to-text.py 文件后,这将显示转录音频文件的最后一个单词及其结束时间:

Last word:  return
Last word end time:  0:00:55.400000

Speech-to-Text API 的使用目前存在请求限制,并在本文档中进行了说明。


推荐阅读