Pau*_*lie 0 javascript html5-audio audiobuffer
我试图将WAV文件放入AudioBuffer中,以便对其进行操作。我之前已经从AudioBuffer创建了WAV文件,并且需要将Float32Array转换为包含Int16值的DataView。我使用了这个方便的功能:
function floatTo16BitPCM(output, offset, input){
for (var i = 0; i < input.length; i++, offset+=2){
var s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,我现在需要做的就是扭转这种情况(从服务器加载WAV文件,因此我不再有原始数据了)。我无法弄清楚该函数中实际发生的情况或数据的转换方式。
这似乎是可行的。我将数据加载到响应类型为“ 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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2190 次 |
| 最近记录: |