Skip to content

Instantly share code, notes, and snippets.

@simonewebdesign
Last active August 16, 2022 21:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simonewebdesign/6753413 to your computer and use it in GitHub Desktop.
Save simonewebdesign/6753413 to your computer and use it in GitHub Desktop.
Play WAV and MP3 files with HTML5 Audio
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>audio test</title>
</head>
<body>
<!-- <audio controls="controls" autoplay>
Your browser does not support the <code>audio</code> element.
<source src="smb_gameover.wav" type="audio/wav">
</audio>
-->
<button class="playWAV">Play WAV</button>
<button class="playMP3">Play MP3</button>
<script>
/**********************
******** AUDIO ********
**********************/
// load and play a sound.
function playSound(path) {
// audio supported?
if (typeof window.Audio === 'function') {
var audioElem = new Audio();
audioElem.src = path;
audioElem.play();
}
}
// event listeners
document.querySelector('.playWAV').addEventListener('click', function(){
playSound('smb_gameover.wav');
});
document.querySelector('.playMP3').addEventListener('click', function(){
playSound('music.mp3');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment