简体   繁体   中英

How to play the same audio file multiple times at once in JavaScript

I'm trying to make a JavaScript based game based around music. I'm trying to play some of the sounds as the player moves, but if the previous audio file has not finished, it ends up either cutting off the first one or just not playing the second. I'm using the audio.play() method.

notes.C2 = new Audio();
notes.C2.src = 'piano/C2.wav';

notes.D2 = new Audio();
notes.D2.src = 'piano/D2.wav';
if (l1.cats.x == 0) {
    notes.C2.play();
}
if (l1.cats.x == 1) {
    notes.D2.play();
}

Edit: I'm also not familiar with APIs and stuff so if possible I wouldn't want to use them. Edit 2: I just realized the problem is that the same audio file cannot be played over itself.

Try this thing

var audio1  = new Audio();
var src1  = document.createElement("source");
src1.type = "audio/mpeg";
src1.src  = "audio/Dombra.mp3";
audio1.appendChild(src1);

var audio2  = new Audio();
var src2  = document.createElement("source");
src2.type = "audio/mpeg";
src2.src  = "audio/(TESBIHAT).mp3";
audio2.appendChild(src2);

audio1.play(); audio2.play();

It work on chrome and firefox.

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