Audio Play Pause Mute Buttons Tutorial

Published :
Author :
Adam Khoury
Audio Workshop is a series of videos in which we will demonstrate how program the Audio object and the Web Audio API using JavaScript. I am going to leave this series open ended, just like we did for the Canvas Bootcamp series. I will also be reading viewer comments as we release each video for the series, which will make the series interactive from start to finish. In this first video you can learn to set up an audio application, work with the Audio object in JavaScript, program play, pause and mute buttons, use CSS to style your custom components and more. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body{ background:#666; } button{ border:none; cursor:pointer; outline:none; } button#playpausebtn{ background:url(images/pause.png) no-repeat; width:12px; height:14px; } button#mutebtn{ background:url(images/speaker.png) no-repeat; width:5px; height:14px; } </style> <script> var audio, playbtn, mutebtn, seek_bar; function initAudioPlayer(){ audio = new Audio(); audio.src = "audio/Stoker.mp3"; audio.loop = true; audio.play(); // Set object references playbtn = document.getElementById("playpausebtn"); mutebtn = document.getElementById("mutebtn"); // Add Event Handling playbtn.addEventListener("click",playPause); mutebtn.addEventListener("click", mute); // Functions function playPause(){ if(audio.paused){ audio.play(); playbtn.style.background = "url(images/pause.png) no-repeat"; } else { audio.pause(); playbtn.style.background = "url(images/play.png) no-repeat"; } } function mute(){ if(audio.muted){ audio.muted = false; mutebtn.style.background = "url(images/speaker.png) no-repeat"; } else { audio.muted = true; mutebtn.style.background = "url(images/speaker_muted.png) no-repeat"; } } } window.addEventListener("load", initAudioPlayer); </script> </head> <body> <button id="playpausebtn"></button> <button id="mutebtn"></button> </body> </html>