How to Download a Binary File Into a Javascript Object using XHR.
This article uses the Korerorero project as an example. Korerorero is an open source implementation of an animated chatbot with voice recognition.
To implement the voice of the chatbot, the voice audio is created by korerorero-marytts service. This data needed to be downloaded async, then stored in memory and passed to the audio player library. The howler.js audio library expects a URL to the file.
To set the stage, the API has returned the URL of the WAV file to download. The following code initiates a GET
request to the audio service and stores the resulting arraybuffer
in memory. This arraybuffer
is then dispatched to the recieveAudio(…)
action.
Note: korerorero-front-end uses redux for state management, axios for network communications, and redux-thunk to manage asynchronicity.
Because howler.js expects a file reference, the code above creates an Object URL, this is a URL that references the memory location where the audio is stored. They look something like this:
> URL.createObjectURL(new Blob())
< "blob:https://www.example.com/d2c2bedd-af4e-4ea8-a4c2-7cfe25884e5d"
They can be used anywhere that is expecting a URL, such as the src
attribute of the audio
tag.
#javascript #redux #typescript #audio #react