如何在JavaScript中更改音频的位置?

时间:2017-03-10 12:40:58

标签: javascript jquery audio

我试图使用滑块来改变音轨的位置。我遇到的麻烦是,当我在滑块上滑动时,音频停止而不是改变位置。我尝试删除我的addeventlistener结束函数,但这并没有解决问题。

非常感谢任何帮助。

HTML:

<audio id="music">
    <source src="media/mexico-music.mp3" type="audio/mpeg"/>
 </audio>
 <button id="playpausebtn" class="play"></button>
 <input id="seekslider" type="range" min="0" max="100" value="0" step="1">
 <input id="volumeslider" type="range" min="0" max="100" value="100" step="1">

JavaScript的:

$(document).ready(function () {
    var music = document.getElementById("music"),
        playpausebtn = document.getElementById("playpausebtn"),
        seekslider = document.getElementById("seekslider"),
        volumeslider = document.getElementById("volumeslider"),
        seeking,
        seekto;

    // PLAY/PAUSE AUDIO
    function playAudio() {
        if (music.paused) {
            music.play();
            playpausebtn.className = "pause";
        } else {
            music.pause();
            playpausebtn.className = "play";
        }
        music.addEventListener('ended', function () {
            playpausebtn.className = "Play";
        });
    }

    // SEEK MUSIC POSITION
    function seek(event) {
        if(seeking) {
            seekslider.value = event.clientX = seekslider.offsetLeft;
            seekto = music.duration * (seekslider.value / 100);
            music.currentTime = seekto;
        }
    }

    // VOLUME CONTROL
    function setVolume() {
        music.volume = volumeslider.value / 100;
    }

    //EVENT HANDLERS
    playpausebtn.addEventListener("click", playAudio);
    seekslider.addEventListener("mousedown", function (event) { seeking = true; seek(event); });
    seekslider.addEventListener("mousemove", function (event) { seek(event); });
    seekslider.addEventListener("mouseup", function () { seeking = false; });
    volumeslider.addEventListener("mousemove", setVolume);
});

1 个答案:

答案 0 :(得分:1)

我建议删除以下行:

seekslider.value = event.clientX = seekslider.offsetLeft;

这是因为您在使用之前设置了seekslider的值,这会产生效果,因为下一行music.duration * (seekslider.value / 100);完全符合您的要求。