DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

Using HTML Audio and Video Elements

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

With HTML5, we are provided numerous tools and tags to work with multimedia. One of the new things that come with HTML5 is the ability to embed audio and video without needing plugins like Flash.

In this article, we’ll look at how to add audio and video elements to a web page and control it with JavaScript.

Adding Audio or Video Elements

To add audio and video elements, we use the audio and video tags respectively. They have a few attributes. They are:

  • autoplay — specifies whether the audio or video will play automatically
  • controls — specifies whether playback controls are shown
  • loop — specifies whether we want to play the clip again once it ends
  • muted — specifies if sound should play or not
  • preload — specifies which part of the clip should be preloaded. It can be auto , which loads everything, metadata, which loads only the metadata, or none, which loads nothing
  • src — the URL for the clip

To embed audio in our web pages, we can write the following:

<audio controls>  
  <source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_OOG_1MG.ogg" type="audio/ogg">  
  <source src="https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg">  
  Your browser does not support the audio tag.  
</audio>
Enter fullscreen mode Exit fullscreen mode

In the code above, we specified the audio in different formats of the audio that we want to load.

Likewise, we can do the same with video:

<video controls width="250">  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">  
  Your browser does not support the video tag.  
</video>
Enter fullscreen mode Exit fullscreen mode

In both pieces of code, then text within the tag is the fallback text in case the browser doesn’t support these tags.

Controlling the Elements with JavaScript

We can customize the functionality of the audio or video element with JavaScript code. The following are methods are available for controlling the playback of audio or video elements:

  • play — start playing the audio or video
  • pause — pausing the audio or video
  • load — reload the audio or video element
  • addTextTrack — add a text track to audio or video
  • canPlayType — check if the browser can play the specified type of audio or video

There’re also some properties that we can set the control the audio or video playback:

  • currentTime — sets the current time of the audio or video in seconds
  • defaultMuted — indicate whether the audio output should be muted by default
  • defaultPlaybackRate — a number indicating the default playback for the media
  • loop — boolean indicating whether we want restart playback after it ends
  • muted — boolean we can set for muting the audio
  • playbackRate — sets the playback rate of the clip
  • volume — change the volume of the audio or video

We can use these methods and value properties as follows. First, we add our clip into our HTML code:

<video controls width="250">  
  <source src="https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4" type="video/mp4">  
  Sorry, your browser doesn't support embedded videos.  
</video>
Enter fullscreen mode Exit fullscreen mode

Then we can add buttons to change various things like the playback rate or muting the audio as follows. First, we add some buttons to let us click to change the settings:

<button id='fast-button'>1.5x speed</button>
<button id='fastest-button'>2x speed</button>
<button id='mute'>Toggle Mute  </button>
Enter fullscreen mode Exit fullscreen mode

Then we add some code to get the button and video elements and set the settings accordingly.

const fastButton = document.querySelector('#fast-button');  
const fastestButton = document.querySelector('#fastest-button');  
const muteButton = document.querySelector('#mute');  
const video = document.querySelector('video');

fastButton.onclick = () => {  
  video.playbackRate = 1.5  
}

fastestButton.onclick = () => {  
  video.playbackRate = 2  
}

muteButton.onclick = () => {  
  video.muted = !video.muted;  
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we get the elements and then in the click event handlers for the buttons, we set the playbackRate and toggle the muted properties for the video.

We can do something similar with the methods. For example, we can add the following buttons:

<button id='play'>Play</button>
<button id='pause'>Pause</button>
Enter fullscreen mode Exit fullscreen mode

Then we can add the following buttons click handlers to play and pause the clip programmatically:

playButton.onclick = () => {  
  video.play();  
}

pauseButton.onclick = () => {  
  video.pause();  
}
Enter fullscreen mode Exit fullscreen mode

This is handy for creating custom video and audio players that don’t use the default browser style, along with the controls attribute for showing or hiding the controls.

Another example is making a seek bar for our clip. We can do that by adding a range slider as follows:

<input type="range" name="time" id='time' min='0'>
Enter fullscreen mode Exit fullscreen mode

Then we can set the max attribute of the slider to the duration of our clip and add an onchange event handler as follows:

timeInput.max = video.duration  
timeInput.onchange = (e) => {  
  video.currentTime = e.target.value;  
}
Enter fullscreen mode Exit fullscreen mode

The let us seek to anywhere from the start to the end of the video as we slide back and forth with the slider.

Events

Audio and video elements also have the following events fired, so we can handle them with event handlers we wish to:

  • canplay — the browser can play the media, but estimates that not enough data will be available to finish playback without stopping to buffer.
  • canplaythrough — browser estimates that playback finish without stopping for more buffering
  • complete — playback ends
  • durationchange — duration has been updated
  • emptied — media has become empty
  • ended — playback ended before the end of the clip was reached
  • loadeddata — the first frame has finished loading
  • loadedmetadata — metadata has been loaded
  • pause — playback is paused
  • play — playback began
  • playing — playback is ready to start after having been paused or delayed due to lack of data
  • progress — fired periodically as browser loads a resource
  • ratechange — playback rate changed
  • seeked —seek operation completed
  • seeking — seek operation began
  • stalled —a user-agent tries to fetch media data, but nothing is coming in
  • suspend — media data loading has been suspended
  • timeupdate — the time indicated by the currentTime attribute has been updated
  • volumechange — volume changed
  • waiting — playback stopped because of a temporary lack of data

Top comments (0)