Wednesday , 14 November 2018
Home / Programming / JavaScript / Audio – Advanced JavaScript Tutorial
Audio
Audio

Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you already know how to use most of things in the audio object. However, there are a couple of key differences when it comes to formats.

Audio Tags

To add audio into your document, then you use the <audio> tags like so.

Like last time, you have to use multiple sources as various browsers support different formats. You can also use the controls attribute to have your browser create controllers for your audio file.

Audio Type

There’s also an audio type in JavaScript for grabbing audio files. Let’s clear out our script and add this bit of code.

To grab an audio file, you simply use the Audio type. You must pass in the location of the audio file relevant to the document and not the script. Once we do that, then we add an event called canplaythrough. This event will fire when our audio file has been downloaded and we’re allowed to play it. We use the play() method right away to play it.

Let’s update our function to this.

Before you start playing any file in JavaScript, you should check if the browser can play it. You use the canPlayType() method to perform this check. This will return true or false depending on the browser. You simply pass in the type/codec you want to check for. If all checks out, then we play the audio file.

Conclusion

The audio and video tags are both similar so you should be able to use the audio object without any trouble now. For more information about audio in JavaScript, then go here.

https://developer.mozilla.org/en-US/docs/Web/HTML/Using_HTML5_audio_and_video

About Jasko Koyn

Check Also

Video Events

Video Events – Advanced JavaScript Tutorial

Video events allow you to tap into what’s currently happening with the video. There are …

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.