Search code examples
javascriptvolumeaudio

Change volume of all sounds in document


i have a little question: is there a way how to change volume of all sounds in document with JavaScript (like <video>, <embed>, <object>,...)?

EDIT

I want to change the volume in document like <body volume="0.5">...Any help?


Solution

  • Okay,

    Here is How I'll do it:

    HTML:

    <body>
      Master Audio Controller:-
      <input type="range" min="0" max="1" step="0.1" value="1.0" id="range">
      <span id="range_value">1.0</span>
      <br/>
      <video controls autoplay loop name="media" class="myVolumeClass">
        <source src="http://www.rbg.wz.cz/adventure/sounds/step.wav" type="audio/x-wav">
      </video>
      <br/>
      <video controls autoplay loop name="media" class="myVolumeClass">
        <source src="http://www.rbg.wz.cz/adventure/sounds/step.wav" type="audio/x-wav">
      </video>
      <br/>
      <video controls autoplay loop name="media" class="myVolumeClass">
        <source src="http://www.rbg.wz.cz/adventure/sounds/step.wav" type="audio/x-wav">
      </video>
      <br/>
    </body>
    

    JavaScript:

    function updateVolume() {
      const newVolume = document.getElementById('range').value;
      document.querySelectorAll('video, audio, embed, object').forEach(element => element.volume = newVolume)
      document.getElementById('range_value').innerText = newVolume
    }
    
    document.addEventListener('DOMContentLoaded', function() {
      /* I'll Suggest to use $(document).ready(function(){ }); If Using JQuery */
      document.getElementById('range').addEventListener('input', updateVolume)
    }
    

    Here is a demo of this code.

    Hope it helps, cheers :)!