JavaScript中录制麦克风音频并提交给DialogFlow

JavaScript中录制麦克风音频并提交给DialogFlow

本文介绍了如何在JavaScript中录制麦克风音频并提交给DialogFlow?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过JavaScript录制麦克风中的音频并将其提交给DialogFlow,而无需通过服务器?

How can I record audio from the microphone in JavaScript and submit it to DialogFlow, without going through a server?

推荐答案

此问题分为两部分:

  1. 如何以DialogFlow格式记录麦克风音频.
  2. 如何通过适当的身份验证将音频实际提交到DialogFlow.

第1部分

为了以DialogFlow可以理解的格式录制麦克风音频,我使用 opus-recorder ,然后使用以下代码转换它返回的Blob:

Part 1

For recording microphone audio in a format DialogFlow will understand, I use opus-recorder, then convert the blob it returns using the code below:

function BlobToDataURL(blob: Blob) {
    return new Promise((resolve, reject)=>{
        const reader = new FileReader();
        reader.addEventListener("loadend", e=>resolve(reader.result as string));
        reader.readAsDataURL(blob);
    }) as Promise<string>;
}

const micRecorder = new Recorder({
    encoderSampleRate: 16000,
    originalSampleRateOverride: 16000, // necessary due to Google bug? (https://github.com/chris-rudmin/opus-recorder/issues/191#issuecomment-509426093)
    encoderPath: PATH_TO_ENCODER_WORKER_JS,
});
micRecorder.ondataavailable = async typedArray=>{
    const audioData = new Blob([typedArray], {type: "audio/ogg"});
    const audioData_dataURL = await BlobToDataURL(audioData);
    const audioData_str = audioData_dataURL.replace(/^data:.+?base64,/, "");

    // here is where you need part 2, to actually submit the audio to DialogFlow
};
micRecorder.start();

第2部分

要将音频数据提交到DialogFlow,请在此处查看我的答案: https://stackoverflow.com/a/57857698/2441655

这篇关于如何在JavaScript中录制麦克风音频并提交给DialogFlow?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:04