javascriptaudiohowler.js

howler.js update volume of a sound


I am working with

howler.js 2.0

but cant seem to get a simple example of updating the volume working. Here some a sample code:

window.sound = new Howl({
 src:'http://example.com/assets/audio/background.mp3',
  loop: true,
  volume: 0.15
});

window.updateVolume = function(value) {
  alert('before update volume:', window.sound.volume());
  sound.volume = value;
  alert('after update volume:', window.sound.volume());
}

I have tried both using volume() function and just volume property. None seem to work.

JsFiddle: https://jsfiddle.net/umx2bdm8/

What am I missing? Also, I noticed that if you click play multiple times, multiple instances of the same sound start playing. I dont want that and hitting play on a particular howl instance should always work with that instance.


Solution

  • If you look at howler.js 2.0’s docs for volume, it shows that volume is a function, not an assignable property, and that you need to pass in the new volume as an argument to set the volume. So you need to do sound.volume(value) instead of sound.volume = value.

    sound = new Howl({
      src: 'http://www.hochmuth.com/mp3/Tchaikovsky_Rococo_Var_orch.mp3',
      loop: true,
      volume: 0.5
    });
    
    updateVolume = function(value) {
      console.log('before update volume:', sound.volume());
      sound.volume(value);
      console.log('after update volume:', sound.volume());
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.0-beta13/howler.min.js"></script>
    
    
    <button onclick="sound.play()">
      Play
    </button>
    <button onclick="updateVolume(0.15)">
      Change volume to 0.15
    </button>

    (I switched the volume values above for demo purposes, so listeners don’t have to worry whether the music will suddenly deafen them when they click the button.)