Xander
Xander

Reputation: 1011

How to change the position of audio in JavaScript?

I'm trying to using a slider to change the position of an audio track. The trouble I'm having is that when I mousedown on the slider the audio just stops rather than altering the position. I tried removing my addeventlistener ended function but that didn't solve the problem.

Any help would be greatly appreciated.

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

Upvotes: 0

Views: 246

Answers (1)

evolutionxbox
evolutionxbox

Reputation: 4122

I would recommend removing the following line:

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

This is because you are setting the value of seekslider before you use it, which is counter productive, as the next line music.duration * (seekslider.value / 100); does exactly what you want.

Upvotes: 1

Related Questions