将int16数组转换为float
问题描述:
我有一个音频文件中的字节数组,我想将其转换为可以处理以过滤音频信号的数据. 我有一个像这样的数组: [239,246,96,247 .....];每个元素都是一个uint8字节
I have an array of bytes from an audio file and I want to convert it into data that I can process to filter the audio signal. I have an array like this: [239,246,96,247.....]; Each element is a uint8 byte
每个2字节(16位)代表一个样本,因此我将此数组转换为一个int16元素数组.
Each 2 bytes(16 bits) represent a sample,so I converted this array into a int16 element array.
然后如何将该数组转换为值在[-1,1]范围内的信号?
How can I then convert this array into a signal with values in the range[-1,1]?
答
您已经拥有带符号的int16,因此您只需要除以该符号的最小和最大int16值即可.
You already have your signed int16's so you just have to divide by the min and max int16 value respective to the sign.
let buffer = new Int16Array([0x0001, 0x7fff, 0x000, 0xffff, 0x8000]);
// [1, 32767, 0, -1, -32768]
let result = new Float32Array(buffer.length);
for(let i=0; i<buffer.length; i++) result[i] = buffer[i] / (buffer[i] >= 0 ? 32767 : 32768);
console.log(result[0], result[1], result[2], result[3], result[4]);
// 0.000030518509447574615 1 0 -0.000030517578125 -1