我目前正在使用以下代码将
Float32Array
转换为 Int32Array
以进行音频处理。
const int32 = new Int32Array(
[...new Float32Array(buffer)].map((float) => {
return float < 0 ? float * 32768 : float * 32767
})
注意三元组,它检查浮点数是否小于
0
,如果为 true,则将浮点数乘以 32768
,否则,如果为 false,则将浮点数乘以 32767
。
该代码在野外有不同的版本,例如,上面是我最终编写此代码的方式https://github.com/zhuker/lamejs/commit/e18447fefc4b581e33a89bd6a51a4fbf1b3e1660
# Float32Array / AudioBuffer 的用法
一些库(例如来自 WebAudio API)以带有值的
形式提供音频数据 在AudioBuffer.getChannelData()
和Float32Array
之间。 lamejs 期望值介于-1.0
和1.0
,因此必须映射值:-32768
32767
另请参阅这篇文章,将
var floatSamples = new Float32Array(44100); // Float sample from an external source
var samples = new Int32Array(floatSamples.length);
for (var i = 0; i < floatSamples.length; i++) {
samples[i] = floatSamples[i] < 0 ? floatSamples[i] * 32768 : floatSamples[i] * 32767;
}
转换为
Float32Array
https://github.com/zhuker/lamejs/issues/55#issuecomment-1959182758
Int16Array
我想做的是找出最短的代码(以字符为单位),以达到预期的结果。
有没有办法在不检查
// Interpolate to -32768 to 32767, which is signed int16
const interpolated = leftChannel.map((n) =>
Math.max(-32768, Math.min(32768, n * (n < 0 ? 32768 : 32767)))
);
中每个单独的浮点的情况下正确执行此转换?