Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

javascript - Converting Float32Array to Uint8Array while Preserving IEEE 754 Representation

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

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

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...