Javascript DOM HTML Audio volume Property set

Introduction

Set audio volume to 20%:

document.getElementById("myAudio").volume = 0.2;

Click the buttons to get or set the volume of the audio player.

View in separate window

<!DOCTYPE html> 
<html> 
<body> 

<audio id="myAudio" controls>
  <source src="sound.ogg" type="audio/ogg">
  <source src="sound.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>/*www. j  a v  a  2s . c o m*/
<p id="demo"></p>
<button onclick="getVolume()" type="button">What is the volume?</button>
<button onclick="setHalfVolume()" type="button">Set volume to 0.2</button>
<button onclick="setFullVolume()" type="button">Set volume to 1.0</button>

<script>
var x = document.getElementById("myAudio");

function getVolume() { 
  document.getElementById("demo").innerHTML = x.volume;
} 

function setHalfVolume() { 
  x.volume = 0.2;
}
   
function setFullVolume() { 
  x.volume = 1.0;
} 
</script> 

</body> 
</html>

The volume property sets or gets the audio volume of an audio.

The value is from 0.0 (silent) to 1.0 (loudest).

The number setting the audio volume of the audio must be a number between 0.0 to 1.0.

Example values:

  • 1.0 is highest volume (100%. This is default)
  • 0.5 is half volume (50%)
  • 0.0 is silent (same as mute)



PreviousNext

Related