Sometime back I was making a browser based game in the html5 canvas tag which had some audio too. The html5 audio tag is an easy option to add sound/music to any webpage. It can play variety of formats like wav, ogg and mp3. However format support itself varies across browsers.
The audio element can be directly added to html in the form of a tag
<audio src="sound.mp3" controls></audio>
The src attribute holds the path/url to the sound file to play. This by default would bring up a ui element on the webpage which will have buttons to play/pause and control the volume. But such an audio player is not always needed or necessary, like in a game, where we need to dynamically or rather programmatically load sound files in the background and play them on a certain event.
The Audio element has a javascript class that can be used to do this in a purely html independant way. Lets see how.
Audio Object
Audio objects can be created in javascript like this.
var aud = new Audio();
aud.src = 'sound.ogg';
//You could also do
var aud = new Audio('sound.ogg');
//Now lets play the music
aud.play();
That way we do not need to create any html elements on the webpage and can modify...
Read full post here
Using the html5 audio element from javascript
The audio element can be directly added to html in the form of a tag
<audio src="sound.mp3" controls></audio>
The src attribute holds the path/url to the sound file to play. This by default would bring up a ui element on the webpage which will have buttons to play/pause and control the volume. But such an audio player is not always needed or necessary, like in a game, where we need to dynamically or rather programmatically load sound files in the background and play them on a certain event.
The Audio element has a javascript class that can be used to do this in a purely html independant way. Lets see how.
Audio Object
Audio objects can be created in javascript like this.
var aud = new Audio();
aud.src = 'sound.ogg';
//You could also do
var aud = new Audio('sound.ogg');
//Now lets play the music
aud.play();
That way we do not need to create any html elements on the webpage and can modify...
Read full post here
Using the html5 audio element from javascript