Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop audio played by audio tag of HTML5

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);
  }
like image 703
Vijay Balkawade Avatar asked Aug 25 '10 14:08

Vijay Balkawade


People also ask

How do I stop audio playing in HTML?

Audio pause() Method The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).

How do I mute audio in html5?

In this article, we mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage.

How do you stop a sound in Javascript?

js | stop() Function. The stop() function is an inbuilt function in p5. js library. This function is used to stop the audio on the web which is playing or gonna played.

How do I turn off audio in react?

Take the reference of the audio file in ReactJS Using Audio Class. Set the default state of the song as not playing. Make a function to handle the Play/Pause of the song. Use the play() and pause() functions of audio class to do these operations.


2 Answers

Try this:

  try
  {
       if(MyAudio != undefined)
       {
          MyAudio.pause();
       }
       MyAudio = new Audio("filename");
       MyAudio.play();
  }
  catch(v)
  {
    //alert(v.message);
  }
like image 141
Lekensteyn Avatar answered Oct 07 '22 20:10

Lekensteyn


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;
like image 29
Duefectu Avatar answered Oct 07 '22 20:10

Duefectu