Home > Mobile >  Cycle a list of audio files on click
Cycle a list of audio files on click

Time:09-28

I have a simple code that plays a list of audio files by clicking each button. This works fine but what I need to 1 button that cycles through the list each time the button is pressed.

I.e.
Click Button = play sound 1
Click again plays sound 2
Click again plays sound 3 etc.

const sounds = ['sound1', 'sound2', 'sound3', 'sound4', 'sound5', 'sound6'];

sounds.forEach(sound => {
    const btn = document.createElement('button');
    btn.classList.add('btn');
    btn.innerText = sound;

    btn.addEventListener('click', () => {
        stopPlaying();
        document.getElementById(sound).play();
    })

    document.getElementById('buttons').append(btn);
})


function stopPlaying() {
    sounds.forEach(sound => {
        const audio = document.getElementById(sound);
        audio.pause();
        audio.currentTime = 0;
    })
}

CodePudding user response:

use an array.

var audios = document.querySelectorAll("audio");
var pointer = 0;
const btn = document.createElement('button');
btn.classList.add('btn');
btn.innerText = "play next";

btn.addEventListener('click', () => {
  // stopPlaying();
  audios[pointer].play();
  pointer  = 1;
  if (pointer >= audios.length) {
    pointer = 0
  }
})

document.body.append(btn)
<audio></audio>
<audio></audio>

CodePudding user response:

I believe you should do two things.

First: Create an array with the songs, in a function that receives a parameter (can be a number to simplify), and return to the musisic to be played or if it is to reset the playlist.

Second: Following this reasoning, in your code, you could put a reset button to reset the playlist, and allow the Play/Pause button control the playlist, advancing it or pausing.

  • Related