howler.js
How to Download a Binary File Into a Javascript Object using XHR.
如何使用XHR将二进制文件下载到Javascript对象中。
This article uses the Korerorero project as an example. Korerorero is an open source implementation of an animated chatbot with voice recognition.
本文以Korerorero项目为例。 Korerorero是具有语音识别功能的动画聊天机器人的开源实现。
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.
为了实现聊天机器人的语音,语音音频由korerorero-marytts服务创建。 该数据需要异步下载,然后存储在内存中并传递到音频播放器库。 howler.js音频库需要文件的URL。
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.
为了做好准备,API返回了WAV文件的URL以进行下载。 以下代码向音频服务启动GET
请求,并将结果arraybuffer
存储在内存中。 然后,将这个arraybuffer
调度到recieveAudio(…)
操作。
Note: korerorero-front-end uses redux for state management, axios for network communications, and redux-thunk to manage asynchronicity.
注意: korerorero前端使用redux进行状态管理,使用axios进行网络通信,使用redux thunk进行异步管理。
response.ts(使用XHR获取二进制文件) (response.ts (GET the binary with XHR))
Source: https://github.com/nzcodarnoc/korerorero-front-end/blob/v0.3.1/src/redux/actions/response.ts
来源: https : //github.com/nzcodarnoc/korerorero-front-end/blob/v0.3.1/src/redux/actions/response.ts
response.ts(与上面相同的文件) (response.ts (same file as above))
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:
因为howler.js需要文件引用,所以上面的代码创建了一个Object URL ,这是一个引用存储音频的内存位置的URL。 他们看起来像这样:
> 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.
它们可以在需要URL的任何地方使用,例如audio
标签的src
属性。
避免内存泄漏 (Avoid Memory Leaks)
According to the Documentation memory needs to be managed manually, this is especially important for long-lived SPAs, and doubly so for mobile platforms which typically have limited memory compared with desktops.
根据文档需要手动管理内存,这对于长期使用的SPA尤其重要,而对于与台式机相比内存通常有限的移动平台则尤其如此。
Each of these must be released by calling
URL.revokeObjectURL()
when you no longer need them.当不再需要它们时,必须通过调用
URL.revokeObjectURL()
释放它们。
Dear reader, at the time of writing this, I had not implemented this important deallocation of memory and so the app has a memory leak. Guess what just went to the top of my to-do list?
亲爱的读者,在撰写本文时,我尚未实现内存的重要重新分配,因此该应用存在内存泄漏。 猜猜是什么才成为我的待办事项清单的首位 ?
翻译自: https://medium.com/@QueenOliviaStR/async-load-an-audio-file-and-play-it-with-howler-js-fefc4f537656
howler.js