Mageek Mageek - 4 months ago 23
Javascript Question

Generate a sound of specific frequency

I found this library : 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?


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)));