Thursday , 17 August 2017
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

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

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

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link