Mageek Mageek - 1 month ago 7
Javascript Question

Generate a sound of specific frequency

I found this library : http://codebase.es/riffwave/ which generate sounds on-the-fly in javascript.

What I want is to have a function which generates a sine wave of a specific frequency.

But the way we use the library is with a lot of math and I wasn't able to make it work.

I tried

for(var i=0;i<10000;i++)data.push(127*(Math.sin(2*Math.PI*f*i)));


but it didn't work.

How can I do it?

Answer

Try this:

var freq = 440;  // Frequency (cycles per second)
var rate = 44100;  // Sample rate (samples per second)
for(var i = 0; i < 10000; i++) {
    var time = i / rate;       
    data[i] = 128 + Math.round(127 * (Math.sin(2 * Math.PI * freq * time)));
}