Tomáš Zato
Tomáš Zato

Reputation: 53318

How do I get microphone data from AudioContext

So, I just found out that you can record sound using javascript. That's just awesome!

I intantly created new project to do something on my own. However, as soon as I opened source code of the example script, I found out that there are no explanatory comments at all.

I started googling and found a long and interesting article about AudioContext that doesn't to be aware of the recording at all (it only mentions remixinf sounds) and MDN article, that contains all the information - succesfully hiding the one I'm after.

I'm also aware of existing frameworks that deal with the thing (somehow, maybe). But if I wanted to have a sound recorder I'd download one - but I'm really curious how the thing works.

Now not only that I'm not familiar with the coding part of the thing, I'm also curious how the whole thing will work - do I get intensity in specific time? Much like in any osciloscope? Or can I already get spectral analysis for the sample?

So, just to avoid any mistakes: Please, could anyone explain the simplest and most straightforward way to get the input data using above-mentioned API and eventually provide a code with explanatory comments?

Upvotes: 3

Views: 5969

Answers (1)

Ivo Tebexreni
Ivo Tebexreni

Reputation: 164

If you just want to use mic input as a source on WebAudio API, the following code worked for me. It was based on: https://gist.github.com/jarlg/250decbbc50ce091f79e

navigator.getUserMedia = navigator.getUserMedia
                      || navigator.webkitGetUserMedia
                      || navigator.mozGetUserMedia;
navigator.getUserMedia({video:false,audio:true},callback,console.log);

function callback(stream){
  ctx = new AudioContext();
  mic = ctx.createMediaStreamSource(stream);
  spe = ctx.createAnalyser();
  spe.fftSize = 256;
  bufferLength = spe.frequencyBinCount;
  dataArray = new Uint8Array(bufferLength);
  spe.getByteTimeDomainData(dataArray);
  mic.connect(spe);
  spe.connect(ctx.destination);
  draw();
}

Upvotes: 3

Related Questions