Skip to content

Play and pause audio in JavaScript

In this short post, learn how to play an audio file and pause audio in JavaScript. This article will also discuss the html tag which was introduced in HTML5.

Advertisements

The tag defines sound, such as music or other audio streams in a html page. The tag is used to embed audio content in an HTML document without requiring any additional plugins.

The supported audio formats in HTML are MP3, WAV, and OGG.

To play audio using JavaScript, first define the audio element in HTML.

<audio id="welcome" controls>
  <source src="welcome.mp3" type="audio/mpeg">
</audio>

If the music in ogg, the type of source should be audio/ogg. In case of wav, it’s audio/wav.

Get the audio element in JavaScript

const welcomeSong = document.querySelector("#welcome");
Advertisements

Play the audio

welcomeSong.play();

Pause the audio

welcomeSong.pause();
See also  How to accept infinite parameters in a JavaScript function?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.