How to Pause or Stop Audio After Few Seconds in JavaScript

In the previous post, I have shown you How to set audio playing time to starting position in JavaScript and here I am again with another useful tutorial on how to pause audio after few seconds in JavaScript Automatically. You can also say that how to pause audio on a particular time using JavaScript.

Using this method which I am gonna show you, you can play audio from a specific time to a specific time using JavaScript.

Pause Audio on a specific time in JavaScript

in order to stop audio on a specific time I am not going to use any setTimeout method or anything like that. Here I am gonna work with simple currentTime and my own logic.

Just create an if condition. Suppose you want to stop the audio after 40 seconds.

Then you can simply do this



if(audio.currentTime>40){
audio.pause();
}

To understand you easily I am giving you an example.

function settime(){
	var audio= document.getElementById("myaudio");
	audio.currentTime=40;
	audio.play();
	console.log(audio.currentTime);
	setInterval(function(){
		if(audio.currentTime>45){
			audio.pause();
				}
			},1000);
		}

Here I have set currentTime to 40. That means audio will be played from 40.

If you don’t know setInterval() method in JavaScript, you may read

Run your JavaScript code every n seconds using setInterval() method

Run JavaScript code or call a function after n seconds

In the if condition I set it to greater than 45. So after 5 seconds, the audio will be stopped automatically.

console.log(audio.currentTime);

This line will print the audio playing current time in the console log and this is not mandatory.

audio.currentTime=40; if you set it to zero then audio will start from the beginning.

How to Play Audio After Few Seconds or Delay in JavaScript

Example: play audio from a specific time and stop audio on a specific time in JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>Audio time set to zero</title>
</head>
<body>
  <audio id="myaudio" src="filename.mp3"></audio>

  <button onclick="settime()">Set time to zero</button>
  <script type="text/javascript">
    
    function settime(){
      var audio= document.getElementById("myaudio");
      audio.currentTime=40;
      audio.play();
      console.log(audio.currentTime);
      setInterval(function(){
        
        if(audio.currentTime>45){
          
          audio.pause();
        }
      },1000);
    }

  </script>
</body>
</html>

Using this you can play a particular portion of audio in JavaScript

If you get a problem in understanding this or you have any question feel free to comment below. We will be happy to sort out your problems.

Bottom Sticky Music Player Source Code in JavaScript and CSS

Leave a Reply

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