这似乎有效。我在响应类型为“arraybuffer”的 ajax 调用中加载数据。否则,响应最终会变成一个字符串,并且处理起来很混乱。然后我转换为 16 位数组。然后我以与 WAV 编码一起使用的方式将其转换为 Float32 数组。我还需要扔掉 WAV 的标题,以及它末尾的一些元数据。
// These are ready to be copied into an AudioBufferSourceNode's channel data.
var theWavDataInFloat32;
function floatTo16Bit(inputArray, startIndex){
var output = new Uint16Array(inputArray.length-startIndex);
for (var i = 0; i < inputArray.length; i++){
var s = Math.max(-1, Math.min(1, inputArray[i]));
output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
}
return output;
}
// This is passed in an unsigned 16-bit integer array. It is converted to a 32-bit float array.
// The first startIndex items are skipped, and only 'length' number of items is converted.
function int16ToFloat32(inputArray, startIndex, length) {
var output = new Float32Array(inputArray.length-startIndex);
for (var i = startIndex; i < length; i++) {
var int = inputArray[i];
// If the high bit is on, then it is a negative number, and actually counts backwards.
var float = (int >= 0x8000) ? -(0x10000 - int) / 0x8000 : int / 0x7FFF;
output[i] = float;
}
return output;
}
// TEST
var data = [ 65424, 18, 0, 32700, 33000, 1000, 50000 ];
var testDataInt = new Uint16Array(data);
var testDataFloat = int16ToFloat32(testDataInt, 0, data.length);
var testDataInt2 = floatTo16Bit(testDataFloat, 0);
// At this point testDataInt2 should be pretty close to the original data array (there is a little rounding.)
var xhr = new XMLHttpRequest();
xhr.open('GET', '/my-sound.wav', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status === 200) {
// This retrieves the entire wav file. We're only interested in the data portion.
// At the beginning is 44 bytes (22 words) of header, and at the end is some metadata about the file.
// The actual data length is held in bytes 40 - 44.
var data = new Uint16Array(this.response);
var length = (data[20] + data[21] * 0x10000) / 2; // The length is in bytes, but the array is 16 bits, so divide by 2.
theWavDataInFloat32 = int16ToFloat32(data, 22, length);
}
};
xhr.send();