So I am trying to make a volume switcher that I can use by pressing UP and DOWN arrow keys on my keyboard.
When I try and log the new volume it has to be set to, this works fine, it gives me the correct value, but then when I try to set my volume on the <audio>
element it does not appear to be working.
Below is my HTML Code:
<audio id="music" controls autoplay>
<source src="" type="audio/mpeg">
</audio>
The src for the <source>
element gets set in a different javascript, it will grab a random audio file.
Below here is my Javascript code:
let music_element = document.getElementById("music");
function setVolume(volume) {
music_element.volume = volume;
}
function getVolume() {
var volume = music_element.volume;
return volume;
}
document.onkeydown = function(e) {
switch (e.keyCode) {
case 38:
var current_volume = getVolume();
var new_volume = current_volume + 0.1;
if (new_volume > 1) {
new_volume = 1;
}
setVolume(new_volume.toFixed(1))
console.log('Set volume to ' + new_volume.toFixed(1));
break;
case 40:
var current_volume = getVolume();
var new_volume = current_volume - 0.1;
if (new_volume < 0) {
new_volume = 0;
}
setVolume(new_volume.toFixed(1))
console.log('Set volume to ' + new_volume.toFixed(1));
break;
}
};
Any help/feedback would be highly appreciated!
2
Answers
It is working for me, here’s a snippet you could have used in your question. Only difference is the part that sets the
src
to themusic_element
. Test if that part works for you.It appears that your code is fine✼, a more likely reason that you have no sound is that you might have sound blocked by the browser. In Chrome do the following:
.
✼ There is a minor discrepancy in that
.keyCode
property is deprecated. Use.key
instead. (see Example)Details are commented in example