5 minutes read

Music makes the world go round, and everyone enjoys listening to music of some kind. There are plenty of resources on the Internet that allow you to listen to songs online. One particular object is responsible for that: it's called Audio Object. It gives us an opportunity to access the HTML <audio> element, which contains the audio files.

Creating an Audio Object

Not only HTML allows you to create DOM elements: it can also be done with JavaScript. An Audio Object can be created by using the following syntax:

let audio = document.createElement("AUDIO");

You can also create audio objects using the new Audio() construction:

let audio = new Audio("path/to/myAudio.mp3");

This is more convenient because you can immediately specify the path to the audio recording we want to insert. If you want to use createElement() to create audio objects, then the link to the file is specified using the property which we will consider below.

To get access to this object, we can use the method we're already familiar with: getElementById(). Let's assume that our HTML <audio> element has the id myAudioID. We call the method getElementById() to access that element by its id:

let audio = document.getElementById("myAudioID"); 

Properties

Just as with any other object, access to the properties of an Audio Object is obtained through a point. Let's take a look at the basic properties of the given object:

let audio = getElementById("myObjectID");
let src = audio.src;
console.log(src);

The src property is responsible for the path to the file (URL). It can be set the same way as any other object property is set:

audio.src = "path/to/myAudio.mp3";

The duration property lets us know the duration of the audio file in seconds:

let duration = audio.duration;
console.log(duration);

These are only a few examples: a full list of Audio Object properties is far more extensive.

Methods

Now let's consider some Audio Object methods. The following method is responsible for reloading the <audio> element:

audio.load();

The following methods are probably the most basic ones:

audio.play();
audio.pause();

As you can guess, the play() method is used for starting the current audio element, and pause() is used for stopping it. Again, this is not a full list, so we encourage you to check out other methods.

Conclusion

Today we learned about the Audio Object, how to create and access it, and what are its basic properties and methods. Be sure to explore the additional sources and challenge yourself with our practical tasks!

230 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo