Sound Effects in JavaScript/Html5

Sound effects in JavaScript / HTML5

HTML5 Audio objects

You don't need to bother with <audio> elements. HTML 5 lets you access Audio objects directly:

var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();

There's no support for mixing in current version of the spec.

To play same sound multiple times, create multiple instances of the Audio object. You could also set snd.currentTime=0 on the object after it finishes playing.


Since the JS constructor doesn't support fallback <source> elements, you should use

(new Audio()).canPlayType("audio/ogg; codecs=vorbis")

to test whether the browser supports Ogg Vorbis.


If you're writing a game or a music app (more than just a player), you'll want to use more advanced Web Audio API, which is now supported by most browsers.

How to play audio?

If you don't want to mess with HTML elements:

var audio = new Audio('audio_file.mp3');
audio.play();

function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}
<button onclick="play()">Play Audio</button>

How do I make JavaScript beep?

It's not possible to do directly in JavaScript. You'll need to embed a short WAV file in the HTML, and then play that via code.

An Example:

<script>
function PlaySound(soundObj) {
var sound = document.getElementById(soundObj);
sound.Play();
}
</script>

<embed src="success.wav" autostart="false" width="0" height="0" id="sound1"
enablejavascript="true">

You would then call it from JavaScript code as such:

PlaySound("sound1");

This should do exactly what you want - you'll just need to find/create the beep sound yourself, which should be trivial.

Advanced audio manipulation in HTML5

There is a method to getUserMedia using HTML5 which allows recording using the computer's microphone. But, it is only supported by Opera at this time.
http://caniuse.com/#feat=stream

Audio playback is supported by all modern browsers.

http://caniuse.com/#feat=audio

Thw Web Audio API will allow the other things you ask for. It does not have full browser support.
http://caniuse.com/#feat=audio-api



Related Topics



Leave a reply



Submit