Skip to content Skip to sidebar Skip to footer

How To Set The Loudness Of Html5 Audio?

In an HTML5 game I'm making, I play a 'thud' sound when things collide. However, it is a bit unrealistic. No matter the velocity of the objects, they will always make the same, rel

Solution 1:

Use the audio element's volume property. From W3:

The element's effective media volume is volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. The loudest setting may be lower than the system's loudest possible setting; for example the user could have set a maximum volume.

Ex: sounds[id].volume=.5;

Solution 2:

You can even play around with the gain and make the volume play louder than 100%. You can use this function to amplify the sound:

functionamplifyMedia(mediaElem, multiplier) {
  var context = new (window.AudioContext || window.webkitAudioContext),
      result = {
        context: context,
        source: context.createMediaElementSource(mediaElem),
        gain: context.createGain(),
        media: mediaElem,
        amplify: function(multiplier) { result.gain.gain.value = multiplier; },
        getAmpLevel: function() { return result.gain.gain.value; }
      };
  result.source.connect(result.gain);
  result.gain.connect(context.destination);
  result.amplify(multiplier);
  return result;
}

You could do something like this to set the initial amplification to 100%:

var amp = amplifyMedia(sounds[id], 1);

Then if you need the sound to be twice as loud you could do something like this:

amp.amplify(2);

If you want to half it you can do this:

amp.amplify(0.5);

A full write up of the function is found here: http://cwestblog.com/2017/08/17/html5-getting-more-volume-from-the-web-audio-api/

Solution 3:

You can adjust the volume by setting:

setVolume = function(id,vol) {
    sounds[id].volume = vol; // vol between 0 and 1
}

However, bear in mind that there is a small delay between the volume being set, and it taking effect. You may hear the sound start to play at the previous volume, then jump to the new one.

Post a Comment for "How To Set The Loudness Of Html5 Audio?"