简体   繁体   中英

Multiple wavesurfer.js players

When I have more than 1 instance on a single page the player doesn't work properly, I figured I'd have to create a foreach cicle of some sorts, if anyone could help me with this issue it would be much appreciated.

Here's what I have:

<script src='https://unpkg.com/wavesurfer.js'></script>
<script>
  duration = document.querySelector('#duration');
current = document.querySelector('#current');
playPause = document.querySelector('#playPause');
var timeCalculator = function (value) {
    second = Math.floor(value % 60);
    minute = Math.floor((value / 60) % 60);
    if (second < 10) {
        second = '0' + second;
    }
    return minute + ':' + second;
};

wavesurfer = WaveSurfer.create({
    container: '#wave',
    waveColor: '#a43152',
    progressColor: '#5b1b2d',
    height: 30,
    barRadius: 2,
    barWidth:3,
    barGap:2,
    scrollParent: false
});

wavesurfer.load('files/$title.mp3');

playPause.addEventListener('click', function (e) {
    wavesurfer.playPause();
});

wavesurfer.on('ready', function (e) {
    duration.textContent = timeCalculator(wavesurfer.getDuration());
});

wavesurfer.on('audioprocess', function (e) {
    current.textContent = timeCalculator(wavesurfer.getCurrentTime());
});

wavesurfer.on('play', function (e) {
    playPause.classList.remove('fi-rr-play');
    playPause.classList.add('fi-rr-pause');
});

//change pause button to play on pause
wavesurfer.on('pause', function (e) {
    playPause.classList.add('fi-rr-play');
    playPause.classList.remove('fi-rr-pause');
});

wavesurfer.on('seek', function (e) {
    current.textContent = timeCalculator(wavesurfer.getCurrentTime());
});
</script>";
        
    

You need to create multiple wavesurfer instances with different IDs. So you can create each one by using a for loop with

container: '#wave'+index

and inside your for loop you will also need to add listeners for play/pause/seek...

The only issue will be loading all mp3s, if you are loading 2-5 smaller files you should be fine, but loading more can slow down your page performance. I recommend using drawBuffer() and then loading mp3s when the user clicks play.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM