lundi 30 décembre 2019

A music player. A few audio files

I make a music player. I don't know what to do to play some music files. I would like an audio player in separate divs, if I click.play, another music file will be played. More precisely, if I click button.play in the first div audio-player, the music file music.mp3 is played, and if I click button.play in the second div audio-player, the music file music1.mp3 is played. Here's my code.

    <div class="audio-player">
        <audio src="music.mp3"></audio>
        <button class="play" autofocus>play</button>
        <div class="seek-bar">
            <div class="fill"><div class="handle"></div></div>
        </div>
    </div>
    <div class="audio-player">
        <audio src="music.mp3"></audio>
        <button class="play" autofocus>play</button>
        <div class="seek-bar">
            <div class="fill"><div class="handle"></div></div>
        </div>
    </div>
var audio = document.querySelector('audio');
var playBtn = document.querySelector('button.play');
var seekBar = document.querySelector('.seek-bar');
var fillBar = seekBar.querySelector('.fill');

var pointerdown = false;

playBtn.addEventListener('click', function(){
    if (audio.paused) {
        audio.play();
    } else {
        audio.pause();
    }
});

audio.addEventListener('timeupdate', function(){
    if(pointerdown) return;

    var p = audio.currentTime / audio.duration;

    fillBar.style.width = p * 100 + '%';
});

function clamp (min, val, max) {
    return Math.min(Math.max(min, val), max);
}

function getP (e) {
    var p = (e.clientX - seekBar.offsetLeft) / seekBar.clientWidth;
    p = clamp(0, p, 1);

    return p;
}

seekBar.addEventListener('pointerdown', function(e){
    pointerdown = true;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';
});

window.addEventListener('pointermove', function(e){
    if(!pointerdown) return;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';
});
window.addEventListener('pointerup', function(e){
    if(!pointerdown) return;

    pointerdown = false;

    var p = getP(e);

    fillBar.style.width = p * 100 + '%';

    audio.currentTime = p * audio.duration;
});



Aucun commentaire:

Enregistrer un commentaire