2

Is it possible to generate a tone based on a specific formula? I've tried googling it, but the only things I could find were about normal sine waves, such as this other SO question. So I was wondering if it is possible to generate tones based on other kinds of formulas?

On that other SO question, I did find a link to this demo page, but it seems like that page just downloads sound files and uses them to just alter the pitch of the sounds.

I've already tried combining sine waves by using multiple oscillators, based on this answer, which works just as expected:

window.ctx = new webkitAudioContext();
window.osc = [];

function startTones() {
  osc[0] = ctx.createOscillator(),
  osc[1] = ctx.createOscillator()
  osc[0].frequency.value = 120;
  osc[1].frequency.value = 240;
  osc[0].connect(ctx.destination);
  osc[1].connect(ctx.destination);
  osc[0].start(0);
  osc[1].start(0);
}

function stopTones() {
  osc[0].stop(0);
  osc[1].stop(0);
}
<button onclick="startTones();">Start</button>
<button onclick="stopTones();">Stop</button>

So now I was wondering, is it possible to make a wave that's not based on adding sine waves like this, such as a sawtooth wave (x - floor(x)), or a multiplication of sine waves (sin(PI*440*x)*sin(PI*220*x))?

PS: I'm okay with not supporting some browsers - as long as it still works in at least one (although more is better).

Community
  • 1
  • 1
Joeytje50
  • 18,636
  • 15
  • 63
  • 95

1 Answers1

4

All (periodic) waves can be expressed as the addition of sine waves, and WebAudio has a function for synthesising a wave form based on a harmonic series, context.createPeriodicWave(real, imag).

The successive elements of the supplied real and imag input arrays specify the relative amplitude and phase of each harmonic.

Should you want to create a wave procedurally, then in theory you could populate an array with the desired waveform, take the FFT of that, and then pass the resulting FFT components to the above function.

(WebAudio happens to support the sawtooth waveform natively, BTW)

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • Oh I didn't know it [supported other waveforms too](http://webaudio.github.io/web-audio-api/#h3_the-oscillatornode-interface). Thanks for that link by the way, it looks like it's quite useful. PS: would you know how the `custom` periodic wave works? – Joeytje50 Dec 22 '14 at 18:08
  • "custom" is what you get when you set the PeriodicWave. – cwilso Dec 22 '14 at 23:27