Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a float32Array from decodeAudioData method, which I want to convert it to Uint8Array while preserving the float32 IEEE 754 audio data.

So far I tried,

var length = float32Array.length;

var emptyBuffer = new ArrayBuffer(length * 4);
var view = new DataView(emptyBuffer);

for (var i = 0; i < length; i++) {
  view.setFloat32(i * 4, float32Array[i], true);
}

var outputArray = new Uint8Array(length);

for (var j = 0; j < length; j++) {
  outputArray[j] = view.getUint8(j * 4);
}

return outputArray;

Edit:

I just need to hold on to the binary representation just as in this answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
599 views
Welcome To Ask or Share your Answers For Others

1 Answer

var output = new Uint8Array(float32Array.length);

for (var i = 0; i < float32Array.length; i++) {
  var tmp = Math.max(-1, Math.min(1, float32Array[i]));
  tmp = tmp < 0 ? (tmp * 0x8000) : (tmp * 0x7FFF);
  tmp = tmp / 256;
  output[i] = tmp + 128;
}

return output;

Anyone got doubt in mind can test this easily with Audacity's Import Raw Data feature.

  1. Download the sample raw data which I decoded from a video file using Web Audio Api's decodeAudioData method.
  2. Convert the Float32Array that sample raw data is filled with to Uint8Array by using the method above (or use your own method e.g. new Uint8Array(float32Array.buffer) to hear the corrupted sizzling sound) and download the uint8 pcm file.

    forceDownload(new Blob([output], { type: 'application/octet-binary' }));

  3. Encode your downloaded data in Audacity using File-> Import -> Raw Data... Encoding should be set to Unsigned 8-bit PCM and Sample Rate should be 16000 Hz since the original decoded audio file was in 16000 Hz.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...