Skip to content Skip to sidebar Skip to footer

Button Stops Multiple Audio Tracks

I am creating a Launchpad, and each row is built of 8 buttons/audio tracks and a stop button. I am wanting each stop button to stop all audio playing on that row when pressed, e.g.

Solution 1:

Hope this gives you some idea.

var stopButton = ...; // select your stop button

stopButton.addEventListener('click', stopAllAudio);

function stopAllAudio(){
    var audios = document.getElementsByTagName('audio'),
        len = audios.length,
        i;
    for (i = 0; i < len; i++){
        audios[i].currentTime = 0;
        audios[i].pause();
        isPlaying[i] = false;
    }
}

You can select element(s) using the following ways:

  1. Select by Id
  2. Select by ClassName
  3. Select by TagName

You can trigger functions on certain element(s) using addEventListener.

You can loop through selected element(s) using for loop.


Solution 2:

If all your rows are well defined, you could do something like this :

HTML

<div class="row">
    <img class="top" src="images/pink.png" onclick="sound(1); this.src = (this.src.endsWith(offD1)? onImgPnk : offD1);"/>
    [...]
    <div class="stop"></div>
</div>

JS

$(document).on('click','.stop',function(){
    $(this).siblings('img.top').each(function(){
        audio[$(this).index()+1].pause();
        audio[$(this).index()+1].currentTime = 0;
        isPlaying[$(this).index()+1] = false;
    });
});

Basicly, you listen to the click on your .stop div.

When one is clicked, you search for all the other img.top elements in the same parent, and then .pause() them one by one.

I used JQuery here because it's way easier & faster. But if you want a pure javascript solution, just tell me.


Post a Comment for "Button Stops Multiple Audio Tracks"