Lower background music volume when autoplay HTML

Viewed 14557

I have a page that has some animal images and when you click on them it plays the sound of the animal, but since its a kid's game I have a background music, but the sound is too loud. I want when the background music plays automatically, the volume changes to 0.5. How can I set a function that does that? I don't want a function based on click, I want it hidden and change the volume automatically.

The function (it's not working)

myAudio = document.getElementById("audio1");

function setHalfVolume() { 
    myAudio.volume = 0.4;
}

HTML

<audio id= "audio1" controls="controls"  onload="setHalfVolume()">
    <source src="Audio\Jaunty Gumption.mp3"  type="audio/mp3">
</audio>
2 Answers

The event you need is called onloadeddata.

Also unless you need access to the myAudio variable from other functions or globally I would suggest moving it into the setHalfVolume function. Give this a try.

Change your HTML to:

<audio id= "audio1" controls="controls" onloadeddata="setHalfVolume()">
    <source src="Audio\Jaunty Gumption.mp3"  type="audio/mp3">
</audio>

Change your JavaScript to:

function setHalfVolume() {
    var myAudio = document.getElementById("audio1");  
    myAudio.volume = 0.5; //Changed this to 0.5 or 50% volume since the function is called Set Half Volume ;)
}

Try adding an event for play on all of the audio elements of interest and calling setHalfVolume in there:

document.querySelector('#audio1').addEventListener('play', setHalfVolume);

You'll also probably want to reset the volume back to normal after

document.querySelector('#audio1').addEventListener('pause', resetVolume);

Where resetVolume and setHalfVolume are declared sort of like:

function setHalfVolume() { 
    document.getElementById("audio1").volume /= 2;
}
function resetVolume() { 
    document.getElementById("audio1").volume *= 2;
}
Related