Mageek Mageek - 1 year ago 80
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?

Answer Source

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)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download