How to play a group of wav files with javascript

Viewed 79

Let's say I have an Html file that look like this:

<div name="piano">
    <div name="a.wav"></div>
    <div name="b.wav"></div>
    <div name="c.wav"></div>
</div>

How would I play all the .wav files mentioned in the piano div simultaneously (when a button is pressed)?

Edit: For clarification, eventually the user will be able to select what notes are played and at what time. This is just a simplified example.

3 Answers

The normal audio element (<audio> or new Audio()) is not appropriate for this use case, as it leaves no method for precise timing. You need to use the Web Audio API.

Use a BufferSourceNode for each note you want to play:

const buffer = await audioContext.decodeAudioData(... audio data ...);
const bufferSourceNode = audioContext.createBufferSource();
bufferSourceNode.buffer = buffer;
bufferSourceNode.connect(audioContext.destination);
bufferSourceNode.start(/* you can use a start time here */);

See also:

If you would like to play it randomly use:

    <audio src="..." id="song1"></audio>
    <audio src="..." id="song2"></audio>
    <audio src="..." id="song2"></audio>
    for(var i = 1; i <= 3; i++){   
       document.querySelector("#song" + i)[0].play();
    }

With html5, you should use the <audio> tag. It have javascript hooks for 'play', 'pause', etc.

You can add the following html;

<button onclick="playA();playB();playC()">Play Audio</button>

with corresponding javascript

var audioA = new Audio('a.wav');
var audioB = new Audio('b.wav'); 
var audioC = new Audio('c.wav');     
function playA() {
      audioA.play();
    }
function playB() {
      audioB.play();
    }
function playC() {
      audioC.play();
    }
Related