Generating sound on the fly with javascript/html5
You can use the Web Audio API in most browsers now (excepting IE and Opera Mini).
Try out this code:
// one context per documentvar context = new (window.AudioContext || window.webkitAudioContext)();var osc = context.createOscillator(); // instantiate an oscillatorosc.type = 'sine'; // this is the default - also square, sawtooth, triangleosc.frequency.value = 440; // Hzosc.connect(context.destination); // connect it to the destinationosc.start(); // start the oscillatorosc.stop(context.currentTime + 2); // stop 2 seconds after the current time
If you want the volume lower, you can do something like this:
var context = new webkitAudioContext();var osc = context.createOscillator();var vol = context.createGain();vol.gain.value = 0.1; // from 0 to 1, 1 full volume, 0 is mutedosc.connect(vol); // connect osc to volvol.connect(context.destination); // connect vol to context destinationosc.start(context.currentTime + 3); // start it three seconds from now
I got most of this from experimenting in chromium while reading the Web Audio API Working Draft, which I found from @brainjam 's link.
I hope that helps. Lastly, it is very helpful to inspect the various objects in the chrome inspector (ctrl-shift-i).
Using the HTML5 audio element
Cross-browser generative sustained audio using JavaScript and the audio
element isn't currently possible, as Steven Wittens notes in a blog post on creating a JavaScript synth:
"...there is no way to queue up chunks of synthesized audio for seamless playback".
Using the Web Audio API
The Web Audio API was designed to facilitate JavaScript audio synthesis. The Mozilla Developer Network has a Web Based Tone Generator that works in Firefox 4+ [demo 1]. Add these two lines to that code and you have a working synth with generative sustained audio upon keypress [demo 2 - works in Firefox 4 only, click the 'Results' area first, then press any key]:
window.onkeydown = start; window.onkeyup = stop;
The BBC's page on the Web Audio API is worth reviewing too. Unfortunately, support for the Web Audio API doesn't extend to other browsers yet.
Possible workarounds
To create a cross-browser synth at present, you'll likely have to fall back on prerecorded audio by:
- Using long prerecorded ogg/mp3 sample tones, embedding them in separate
audio
elements and starting and stopping them upon keypress. - Embedding an swf file containing the audio elements and controlling playback via JavaScript. (This appears to be the method that the Google Les Paul Doodle employs.)
Web Audio API is coming to Chrome. See http://googlechrome.github.io/web-audio-samples/samples/audio/index.html
Follow the directions in "Getting Started" there, and then check out the very impressive demos.
Update(2017): by now this is a much more mature interface. The API is documented at https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API