How to set the loudness of HTML5 audio?

31,671

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:

function amplifyMedia(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.

Share:
31,671
corazza
Author by

corazza

flowing.systems

Updated on July 09, 2022

Comments

  • corazza
    corazza almost 2 years

    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, relatively loud "thud" sound. What I'd like to do is to have that sound's loudness depend on velocity, but how do I do that? I only know how to play a sound.

    playSound = function(id)
    {
        sounds[id].play();
    }
    

    sounds is an array full of new Audio("url")'s.

  • corazza
    corazza about 12 years
    sounds[id].volume(vol) gives "Uncaught TypeError: Property 'volume' of object #<HTMLAudioElement> is not a function"
  • corazza
    corazza about 12 years
    Thanks for the answer and for the tip, +1! How big is the pause usually? My sound are mostly < 1 second in length, will that present problems?