How to record microphone audio in JavaScript and submit to DialogFlow?

南笙酒味 提交于 2019-12-13 08:08:50

问题


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


回答1:


There are two parts to this question:

  1. How to record microphone audio in a format DialogFlow will understand.
  2. How to actually submit that audio to DialogFlow, with proper authentication.

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 = 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();

Part 2

To submit the audio-data to DialogFlow, see my answer here: https://stackoverflow.com/a/57857698/2441655



来源:https://stackoverflow.com/questions/57859703/how-to-record-microphone-audio-in-javascript-and-submit-to-dialogflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!