While working on my Pomodoro Timer and testing out the Notifications API, I decided I wanted to add in some sounds. I figured that notifications might not always be ideal when using a timer and that sometimes a good old fashioned timer can be a much better tool. I discovered information on the HTMLAudioElement and began incorporating a break sound and a work sound into my project.

The first step was to create a couple of sounds and save them into my project file structure. Then, I referenced them using the Audio constructor. This will load the sound files, but will not play them.

workSound = new Audio("work.wav");
breakSound = new Audio("break.wav");

The next step was to play the sound when I need it. Anytime my Pomodoro is at zero, I play a sound. For example, if it’s time for the break period, then I play the break sound. Since the audio file was very short, I didn’t have to stop playback.

if($(".timer").text() === "0:00"){
  if(type === "break"){
    breakSound.play();
  }
}

After I finished my project, I began testing out the audio. I noticed the sounds weren’t playing on mobile but were working fine everywhere else. I did some digging and found out that executing the code on page load wouldn’t work for mobile. The code to load the sound must execute after user interaction. I moved the code so it runs when the user clicks “Start” to begin the timer.

$(".start").click(function(){
  workSound = new Audio("work.wav");
  breakSound = new Audio("break.wav");
});

Now the sounds were working but only if I played them inside the “Start” click event. I kept digging and found out that it’s possible to control the playback outside of the click event if you play and pause them first. I updated my code to play and pause each sound immediately after loading. This doesn’t play the sound at all since pause is called immediately.

$(".start").click(function(){
  workSound = new Audio("work.wav");
  breakSound = new Audio("break.wav");
  workSound.play();
  workSound.pause();
  breakSound.play();
  breakSound.pause();
});

After I made this change, the sounds loaded fine on mobile. Success! Check out my Github repo here.

Leave a Reply

Your email address will not be published. Required fields are marked *