Search code examples
javascripthtmlreplacehtml5-audio

How can I change multiple audio sources at once?


I want to change with one click multiple source directories from multiple audio elements at once.

I'm trying to make a small 4-track player with a list of songs which one can choose from and listen to the stems of the selected song. This is the player so far:

HTML:

<div class="list-of-songs">
  <button id="song1" onclick="playsong1()">Song 1</button>
  <button id="song2" onclick="playsong2()">Song 2</button>
  <button id="song3" onclick="playsong3()">Song 3</button>
</div> 

<div class="multitrack__control-panel">
    <button id="pause" onclick="pause()"></button>
    <button id="play" onclick="play()"></button>
    <button id="stop" onclick="stop()"></button>
        
    <audio id="track1" class="stem" src="audio/song1track1.wav"></audio>
    <audio id="track2" class="stem" src="audio/song1track2.wav"></audio>
    <audio id="track3" class="stem" src="audio/song1track3.wav"></audio>
    <audio id="track4" class="stem" src="audio/song1track4.wav"></audio>
</div>

JS:

var track1 = document.getElementById("track1");
var track2 = document.getElementById("track2");
var track3 = document.getElementById("track3");
var track4 = document.getElementById("track4");

/* Play */

function play() {
    track1.play();
    track2.play();
    track3.play();
    track4.play();
}

/* Pause */

function pause() {
  track1.pause();
  track2.pause();
  track3.pause();
  track4.pause();
}

/* Stop */

function stop() {
  track1.pause();
  track2.pause();
  track3.pause();
  track4.pause();
  track1.currentTime = 0;
  track2.currentTime = 0;
  track3.currentTime = 0;
  track4.currentTime = 0;
}

I am Javascript beginner, so I don't really know how to start doing the code for changing all the audio sources at the same time. I thought that using buttons to select the songs is good, but I have no problem in replacing them with an HTML List or something similar.


Solution

  • If you want to change the source of an <audio>, just set the audio source in its src attribute:

    document.getElementById("track1").src = "path/audio.mp3";
    

    In this case, you can change all those <audio> sources at the same time using a loop:

    const 
        sources = ["audio1.wav", "audio2.wav", "audio3.wav", "audio4.wav"],
        audioTags = document.querySelectorAll(".stem");
    
    audioTags.forEach((audio, index) => audio.src = `audio/${sources[index]}`);
    

    Basically I just set every element in the sources array as the source of each <audio>. I don't know what are you exactly want to do, but I think this could give you an idea on how to do it.