HTML and CSS Reference
In-Depth Information
<button onClick="handleEvent(this);">Pause Audio</button>
<button onClick="handleEvent(this);">Audio On</button>
<button onClick="handleEvent(this);">Audio Off</button>
</body>
<script>
var player = new Audio ();
if (document.createElement('audio').canPlayType('audio/ogg')) {
//play ogg file
player.src = 'someAudioFile.ogg';
} else if (document.createElement('audio').canPlayType('audio/mpeg')) {
//play mp3 file
player.src = 'someAudioFile.mp3';
} else if (document.createElement('audio').canPlayType('audio/mp4')) {
//play aac file
player.src = 'someAudioFile.aac';
} else {
//Flash or Silverlight failover
}
function handleEvent (event) {
var t = event.textContent;
switch (t) {
case 'Play Audio' :
player.play();
break;
case 'Pause Audio' :
player.pause();
break;
case 'Audio On' :
player.volume=1;
break;
case 'Audio Off' :
player.volume=0;
break;
}
console.log(t);
}
</script>
</html>
As you can see from the example, you remove the
audio
element from the HTML markup and instead add it to
the JavaScript. The first thing you do is create the buttons to toggle your audio play/pause and sound on/off. Next
you head into the JavaScript where you create a new audio object by writing the lines
var player = new Audio ();
.
From there, you check to see which audio format the browser can play back. In this conditional check, you use the
canPlayType
method to determine whether it's OGG, MP3, or AAC. Once you determine what the browser can play,
you assign the specific audio format that you converted to the player's source attribute by writing
player.src =
'someAudioFile'
. From there you can kick things off by clicking the Play Audio button, which runs through the
case
statement called
handleEvent
. Lastly, you handle all the specific events by attaching the
play()
or
pause()
method
to the
player
object, as well as adjusting the volume to 1 or 0. Give it a shot for yourself! Also, keep on top of the