Play a sound in a Webbrowser

Problem:

You want to play some sounds in a webbrowser.

Solution

Modern Browsers have a fancy integrated AudioContext that allows you to play sounds. Here is an example (JavaScript Code):

// get the AudioContext
window.AudioContext = window.AudioContext || window.webkitAudioContext;

// Initialize audio context
var context = new AudioContext();

// Create an oscillator ... via this oscillator we can then play different sounds
var oscillator = context.createOscillator();
oscillator.frequency.value = 440; // this is an "A"
oscillator.type = "square";

// attach the oscillator to the sound output
oscillator.connect(context.destination);

oscillator.start(0); // start the oscillator (0=now) ...
oscillator.stop(1);  // stop playing this sound after 1 second