EricMc
EricMc

Reputation: 13

Toggle audio "start/stop" with click of image

Could someone please help me add some simple functionality to this string?

Here is what I use to allow people to click on an image and play an audio file...the song plays until its over and wont stop. I would like to allow people to click it a second time to stop the song, and reset it back to the beginning:

$(document).ready(function()
{
    var element = $('#starspangledbanner');

    var audio = new 
    Audio('http://siteassets.starspangledbanner.mp3');

element.click(function(e)
{
    e.preventDefault();
    audio.play();
});

}); 

Thanks in advance.

Upvotes: 1

Views: 379

Answers (1)

Jitu Raiyan
Jitu Raiyan

Reputation: 536

You can follow this code. It's very easy and woks fine:

$(document).ready(function(){

    var element = $('#starspangledbanner'),
    audio = new Audio('http://siteassets.starspangledbanner.mp3');

  element.click(function(e){

    e.preventDefault();
    
    if(audio.paused){
      audio.play();
    }else{
      audio.pause();
      audio.currentTime = 0;
    }
  });
});

Upvotes: 1

Related Questions