Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play pcm data by webAudio API

Hi I am working on WebAudio API . I read HTML5 Web Audio API, porting from javax.sound and getting distortion link but not getting goodquality as in java API.I am getting PCM data from server in signed bytes . Then I have to changed this into it 16 bit format . for changing I am using ( firstbyte<<8 | secondbyte ) but I am not able to get good quality of sound . is there any problem in conversion or any other way to do for getting good quality of sound ?

like image 230
user894554 Avatar asked Jan 03 '12 10:01

user894554


1 Answers

The Web Audio API uses 32-bit signed floats from -1 to 1, so that's what I'm going to (hopefully) show you how to do, rather than 16-bit as you mentioned in the question.

Assuming your array of samples is called samples and are stored as 2's compliment from -128 to 127, I think this should work:

var floats = new Float32Array(samples.length);
samples.forEach(function( sample, i ) {
  floats[i] = sample < 0 ? sample / 0x80 : sample / 0x7F;
});

Then you can do something like this:

var ac = new webkitAudioContext()
  , ab = ac.createBuffer(1, floats.length, ac.sampleRate)
  , bs = ac.createBufferSource();
ab.getChannelData(0).set(floats);
bs.buffer = ab;
bs.connect(ac.destination);
bs.start(0);
like image 117
Kevin Ennis Avatar answered Sep 21 '22 23:09

Kevin Ennis