Alexandre Khoury
Alexandre Khoury

Reputation: 4022

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?

Upvotes: 4

Views: 4008

Answers (1)

Ken Fehling
Ken Fehling

Reputation: 2111

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

Upvotes: 5

Related Questions