Js音频音量滑块

问题描述 投票:1回答:1

我对此并不陌生,我有一个问题。如何放置音量滑块?谢谢!!目前暂时找不到适合我的任何代码,希望对您有所帮助

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>
javascript html audio html5-audio volume
1个回答
0
投票

您可以使用输入范围,我认为可以使用js控制音量或使用本机控件

所以为什么不只在html上使用<audio>元素?您可以给属性controls,然后甚至不需要$("#play-pause-button")

<audio src="your_src" controls="true">

或者是由于样式?如果是这样,那么这里是一个替代方案:

<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');
});

最后选项:使用库进行音频控制。

另外,此代码非常糟糕且重复,建议不要再使用jquery,因为它在这里几乎没有缩短代码的时间

© www.soinside.com 2019 - 2024. All rights reserved.