Search code examples
jqueryhtmlaudiovideovolume

Setting <audio> element to 50% volume when <video> is playing


Hey everyone i hope you can answer this :)

Basically i have a few html 5 videos in my index.html with background audio auto playing.

What i want to happen is reduced the background audio to 50% when the video tag is playing. Would be good if i could use a class to target all video elements if possible :) if the user exits the video it turns the volume back to 100%

Im currently using jQuery for my project so a solution in jQuery would be great!

Currently i think it would be along the lines of this....

// to reduce volume to 50%. im not sure what the code would be to reduce volume ? maybe 0.5 or something ?

    $("video").click(function(){
        $(audio).mute();
    });

// turn volume back to 100% once exit button is clicked

    $(".exit").click(function(){

    });

Solution

  • I think audio.volume = 0.5 should provide the desired result (reduce volume to 50%) and audio.volume = 1.0 to set the volume back to 100%. See MDN Docs for more details.

    See snippet below (click the buttons and look at the volume controls bar):

    var $audio = $('#audio-test').get(0);
    
    $('#set-volume-50').click(function(){
      $audio.volume = 0.5;
    });
    
    $('#set-volume-100').click(function(){
      $audio.volume = 1.0;
    });
    button {
      display: block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <audio id="audio-test" controls="controls">
      Your browser does not support the <code>audio</code> element.
      <source src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" type="audio/ogg">
    </audio>
      <button id="set-volume-50">Set volume to 50%</button>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
      <button id="set-volume-100">Set volume to 100%</button>