Reputation: 43
I am new to this and I have a question. how can i put a volume slider? Thank you!! I can't find any code for the moment that works for me, I hope your help
HTML: <a id="play-pause-button" class="fa fa-play">
JavaScript:
<script type="text/javascript">
var audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
$('#play-pause-button').on("click",function(){
if($(this).hasClass('fa-play'))
{
$(this).removeClass('fa-play');
$(this).addClass('fa-pause');
autoplay = true;
audio.play();
audio.muted = false;
}
else
{
audio.muted = true;
$(this).removeClass('fa-pause');
$(this).addClass('fa-play');
}
});
audio.onended = function() {
$("#play-pause-button").removeClass('fa-pause');
$("#play-pause-button").addClass('fa-play');
};
</script>
Upvotes: 4
Views: 17982
Reputation: 170
I've tested this and it works.
HTML
<input type="range" id="volume-control">
JS
let audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
let volume = document.querySelector("#volume-control");
volume.addEventListener("change", function(e) {
audio.volume = e.currentTarget.value / 100;
})
I hope it helps
Upvotes: 11
Reputation:
You can either use an input range and I think control the volume with js or use the native controls
So why not just use an <audio>
element on the html? you can give the attribute controls
and then you won't even need $("#play-pause-button")
<audio src="your_src" controls="true">
Or is it due to styling? If so then here's an alternative:
<input id="volume-control" type="range" min="0" max="100" value="50">
const audio = new Audio("http://21273.live.streamtheworld.com/LOS40_DANCE.mp3");
const configure = $("#play-pause-button");
const range = $("#volume-control");
configure.on("click", function () {
const hasPlayClass = configure.hasClass("fa-play");
//in nativejs its .classList.toggle() idk about jquery but here's my guess
configure.toggleClass("fa-play");
configure.toggleClass("fa-pause");
audio.muted = hasPlayClass;
if (hasPlayClass) {
//did you mean audio.autoplay? Used to be autoplay
audio.autoplay = true;
audio.play();
} else {
audio.pause();
}
});
range.on("change", () => {
audio.volume = range.value;
});
audio.on("ended", function () {
configure.removeClass('fa-pause');
configure.addClass('fa-play');
});
Last option: use a library for audio controls.
On a different note this code was very bad and repetitive, would recommend not using jquery any further since it barely shortened the code here
Upvotes: 0