Play an audio and set volume with JS

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Play an audio and set volume with JS

I'm trying to create a script for a web page that has an audio like this:

Code: Select all

<div class='class1' id='id1'>
<audio src='link_to_audio' controls='' preload='none' controlslist='nodownload'>
</audio>
</div>
What I need to do is a script that plays the audio and sets its volume at 50%. How to do?

MarPlo Posts: 186
Since the audio tag is a child of #id1 you can use document.querySelector().

To set the volume to 50%, simply use audioElem.volume = 0.5;

Code: Select all

var audioElem = document.querySelector('#id1 audio');
audioElem.volume = 0.5;
audioElem.play();