Page 1 of 1

Play an audio and set volume with JS

Posted: 07 Dec 2020, 07:20
by Marius
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?

Play an audio and set volume with JS

Posted: 07 Dec 2020, 09:19
by MarPlo
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();