简体   繁体   English

压缩 Javascript 中的音频缓冲区大小

[英]Compress Audio Buffer size in Javascript

My main goal is to compress an audio file to reduce its size with JavaScript.我的主要目标是使用 JavaScript 压缩音频文件以减小其大小。 But the tricky part are all the restrictions and requirements I should complain to for my use case:但棘手的部分是我应该为我的用例抱怨的所有限制和要求:

  • Can I compress an audio file with the Web Audio API (or libraries based on it)?我可以使用 Web Audio API(或基于它的库)压缩音频文件吗?
  • Ideally my code should run in the browser as well as NodeJS.理想情况下,我的代码应该在浏览器和 NodeJS 中运行。 For Node, where I am already using the Web Audio API I rely on a library - https://www.npmjs.com/package/web-audio-api for the support;对于 Node,我已经在使用 Web 音频 API 我依赖一个库 - https://www.npmjs.com/package/web-audio-api So ideally I should be able to easily adapt the solution you propose for browser JS in Node as well.因此,理想情况下,我也应该能够轻松地调整您为 Node 中的浏览器 JS 提出的解决方案。
  • For Node I wouldn't want to use ffmpeg or any derivatives, since they rely on native binaries to run and that complicates the runtime when I try to deploy to Google Cloud functions and Azure Functions.对于 Node,我不想使用 ffmpeg 或任何衍生产品,因为它们依赖于本机二进制文件来运行,当我尝试部署到 Google Cloud 函数和 Azure 函数时,这会使运行时复杂化。
  • Currently I have the audio content as an AudioBuffer , so ideally the solution should be able to handle such data structures and shouldn't require filesystem interaction.目前,我将音频内容作为AudioBuffer ,因此理想情况下,该解决方案应该能够处理此类数据结构并且不需要文件系统交互。

In my opinion a library or an algorithm for data size reduction based on the Web Audio API AudioBuffer would be the best solution because even if it is not compatible with the NodeJS library for audio, hopefully I will be able to patch it so it works in my use case.在我看来,基于 Web 音频 API AudioBuffer 的库或用于减少数据大小的算法将是最好的解决方案,因为即使它与用于音频的 NodeJS 库不兼容,希望我能够修补它以便它在我的用例。

I've found an audio encoder javascript library which works in both Node and Browser called lamejs .我找到了一个音频编码器 javascript 库,它可以在节点和浏览器中运行,名为lamejs

So what I needed to achieve could be done as follows:所以我需要实现的可以如下完成:

const mp3encoder = new lamejs.Mp3Encoder(1, SAMPLE_RATE, KBPS);
let samples = audioBuffer.getChannelData(0).map(x => x * 32767.5);
const encoded = mp3encoder.encodeBuffer(samples);
mp3Data.push(encoded);
mp3Data.push(mp3encoder.flush());

Note that you need to normalize the audio volume, because in a typical AudioBuffer data is stored as a float between 0 and 1, that's why when reading the channel data you should multiply it by 32767.5 to be compatible with lamejs ;请注意,您需要标准化音频音量,因为在典型的 AudioBuffer 中,数据存储为 0 和 1 之间的浮点数,这就是为什么在读取通道数据时应将其乘以 32767.5 以与lamejs兼容;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM