How to Play Audio After Few Seconds or Delay in JavaScript

In this tutorial, I will show you how easily you can play audio after few seconds or some time delay easily using JavaScript.

Here we gonna create an HTML file with an audio tag and an audio src file. Then we will load it in our browser. Thereafter, We will create a JavaScript function to play that audio with some delay so that it plays after a certain period of time.

To see the video tutorial play this video



Play audio after few seconds in JavaScript

In this previous post How to Play Audio After The Page Loads in HTML With JavaScript I have described fully.

You can click on the above link to learn how to play audio after page load using JavaScript.

<script type="text/javascript">
    }, 8000)

You can see, here I have used setTimeout function to achieve the delay.

}, 8000)ods

This is the main function to play audio after 8 seconds.

// your code goes here
}, enter delay time in miliseconds)

You may also interested in,

Alert Before Leaving A Web Page Using JavaScript jQuery

Bottom Sticky Music Player Source Code in JavaScript and CSS

To check if your function is working or not you can use console log.

console.log('your audio is started just now');

This line will add a console message when the audio starts playing.

You can test the below code

<!DOCTYPE html>
  <title>My Audio</title>

  <audio src="mysong.mp3" id="my_audio" loop="loop"></audio>
  <script type="text/javascript">
      console.log('your audio is started just now');
    }, 8000)

Just put your audio path in the src attribute.

loop will play the audio file repeatedly.

You may also read,

How to set audio playing time to starting position in JavaScript

5 responses to “How to Play Audio After Few Seconds or Delay in JavaScript”

  1. Jankovix says:

    How to delay mp3 stream, in seconds? Not pause, but delay.

  2. Jankovix says:

    In fact this is ok code, but how to get output from this new delayed file?
    What i need is a link to delayed mp3, not to original.

    • Saruque Ahamed Mollick says:

      Here we are doing nothing with the actual MP3 file. We are just adding a JavaScript function to play the Mp3 with some delay.
      But as per your comment, you want to deal with the actual mp3 file. Do you want a Mp3 file where there will be no sound in the first few seconds and then the sound will be started after few seconds?

Leave a Reply

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