15

I am new to HTML5 and I am exploring HTML5 features. There I came across audio tag.
I written code with it to play sound files.
I am having one problem with this tag. On button click, I want to change the sound file stopping the previous one.
I searched a lot but didn't find anything. Please help me to stop the sound played by audio tag.
Here is my code;

  try
  {
       if(MyAudio != undefined)
       {
          MyAudio = null;
       }
       MyAudio = new Audio("filename");
       MyAudio.play();
  }
  catch(v)
  {
    //alert(v.message);
  }
VJOY
  • 3,752
  • 12
  • 57
  • 90

2 Answers2

12

Try this:

  try
  {
       if(MyAudio != undefined)
       {
          MyAudio.pause();
       }
       MyAudio = new Audio("filename");
       MyAudio.play();
  }
  catch(v)
  {
    //alert(v.message);
  }
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
3

As commented in this cuestión: HTML5 Audio stop function, a better solution could be:

var sound = document.getElementById("audio");
sound.pause();
sound.currentTime = 0;
Community
  • 1
  • 1
Duefectu
  • 1,563
  • 4
  • 18
  • 37