我有一些8位PCM格式的音频缓冲区需要通过网络音频播放,只能接受签名的32位PCM.现在我有一些pcm_u8数据的ArrayBuffer(来自Uint8array).如何将其转换为Float32Array?
此函数将ArrayBuffer转换为Float32Array
var convertBlock(buffer) { // incoming data is an ArrayBuffer var incomingData = new Uint8Array(buffer); // create a uint8 view on the ArrayBuffer var i, l = incomingData.length; // length, we need this for the loop var outputData = new Float32Array(incomingData.length); // create the Float32Array for output for (i = 0; i < l; i++) { outputData[i] = (incomingData[i] - 128) / 128.0; // convert audio to float } return outputData; // return the Float32Array }
这个将Uint8Array转换为Float32Array
var convertBlock(incomingData) { // incoming data is a UInt8Array var i, l = incomingData.length; var outputData = new Float32Array(incomingData.length); for (i = 0; i < l; i++) { outputData[i] = (incomingData[i] - 128) / 128.0; } return outputData; }
ECMAScript 2015及以后版本TypedArray.from
将任何类型化数组(实际上是任何可迭代数组)转换为指定的类型化数组格式.
因此,将Uint8Array转换为Float32Array现在就像以下一样简单:
const intArray = new Uint8Array() const floatArray = Float32Array.from(intArray)