使用MediaRecorder API和react创建的音频,谷歌语音到文本返回空转录



我正在研究一个关于将语音转录成文本的功能,我正在使用谷歌语音与nextjs/react的文本api。我使用浏览器的MediaRecorder api录制音频。用它录制的音频,如果我在谷歌语音文本中使用,它返回一个空的转录。但是如果我用Audacity软件录制的音频,它将返回转录。

下面是我的客户端代码:
const startRecording = () => {
navigator.mediaDevices
.getUserMedia({ audio: true })
.then((stream) => {
const recorder = new MediaRecorder(stream, {
mimeType: "audio/webm; codecs=opus",
bitsPerSecond: 128000,
sampleRate: 48000,
echoCancellation: true,
noiseSuppression: true,
channelCount: 1,
});
const chunks = [];
recorder.addEventListener("dataavailable", (event) => {
chunks.push(event.data);
});
recorder.addEventListener("stop", () => {
const blob = new Blob(chunks, { type: "audio/wav" });
const url = URL.createObjectURL(blob);
setAudioUrl(url);
setRecording(false);
setAudioBlob(blob); // Update the audioBlob state variable
});
recorder.start();
setMediaRecorder(recorder);
setRecording(true);
})
.catch((error) => {
console.log(error);
});
};
这是我的服务器代码:
async function transcribeContextClasses() {
const file = fs.readFileSync("public/audio/1680169074745_audio.wav");
const audioBytes = file.toString("base64");

const audio = {
content: audioBytes,
};
const speechContext = {
phrases: ["$TIME"],
};
const config = {
encoding: "LINEAR16",
sampleRateHertz: 48000,
languageCode: "en-US",
speechContexts: [speechContext],
};
const request = {
config: config,
audio: audio,
};
const [response] = await speechClient.recognize(request);
const transcription = response.results
.map((result) => result.alternatives[0].transcript)
.join("n");
console.log(`Transcription: ${transcription}`);
}

现在我将录制的音频保存为文件,并手动输入到我的服务器端代码中,以便我可以测试从其他软件录制的其他音频。

我能够解决我的问题。我只是改变了我的编码从这个:encoding: "LINEAR16"到这个:encoding: 'WAV'因为我使用的是wav格式。