howler.js update volume of a sound
Asked Answered
E

1

7

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.

Extirpate answered 29/5, 2016 at 0:45 Comment(0)
K
9

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.)

Kassia answered 29/5, 2016 at 1:8 Comment(2)
Do you also know why multiple instances of the sound play if you hit play several times?Extirpate
No, I don’t know why – the docs for play don’t mention that that is supposed to happen. But I know that you can fix it by changing the HTML to onclick="sound.stop(); sound.play()".Waterbuck

© 2022 - 2024 — McMap. All rights reserved.