我需要通过前端录制音频。我正在使用React Mic和Mic-recorder到-mp3 ReactJS库。一切都很好,我正在设法下载音频并听到它。尽管如此,我需要将其上传到后端,这样我就可以使用Google SpeechToText API从音频中提取文本。
这是我使用的脚本,但没有返回任何结果,我认为这是因为录制的音频没有正确的编码。
require "google/cloud/speech"
require 'json'
# Instantiates a client
speech = Google::Cloud::Speech.new
# The name of the audio file to transcribe
file_name = "./newmp3.mp3"
# The raw audio
audio_file = File.binread file_name
encoding = :LINEAR16
# The audio file's encoding and sample rate
config = {
encoding: "LINEAR16",
language_code: "pt-BR",
model: "default",
sample_rate_hertz: 16000
}
audio = { content: audio_file }
# Detects speech in the audio file
response = speech.recognize(config, audio)
results = response.results
puts response
您正在向API发送一个mp3文件,但您告诉它该文件编码为LINEAR16(PCM数据(。这是行不通的。
根据语音API文档,MP3仅通过测试版API支持。
解决这个问题的一个简单方法是使用一个简单的外部音频编码器,如ffmpeg,并在发送之前将其转换为FLAC:
ffmpeg -i input.mp3 output.flac
然后将FLAC
设置为encoding
设置的音频类型。但请记住,使用此方法上传的音频不能超过1分钟。上传较长的文件必须使用谷歌云服务器进行异步存储。