0

I am working on a program which plays audio files creating "melodies". The melodies are randomly created and then performed. The pitches are played in intervals of 1-5 seconds. The audio files are about 4 seconds long. At the start of the program I load all the notes, 40-80, and then simply play them when needed.

(The numbers in the array are pitch numbers.) The eventual output is something like this:

audioFile[80].play();
audioFile[64].play();
audioFile[65].play();

But sometimes the same note is performed twice:

audioFile[65].play();
audioFile[65].play();

or:

audioFile[65].play();
audioFile[63].play();
audioFile[72].play();
audioFile[65].play();

In this case 65 is heard only once because the second 65 is waiting for the first to finish, and sometimes it is still playing by the time the second 65 needs to play.

What can I do to make overlapping of the same audio file possible? Thanks!


Context code

Performing a pitch:

let loadedAudioArr=[];
function playPitch(y){ //y = pitch int 
    loadedAudioArr[y].play();
}

Loading all the sounds:

function loadSounds(x,r,rr){ //x = instrument; r = range lower; rr = range upper
    for (var z=r; z<=rr; z++){
        loadedAudioArr.push(new Audio ("../audio"+"/"+x+"/"+z+".mp3"));
    }
}

Performing 2 notes, wait, repeat ...

for (var i=0; i<=sequencedNotes-1; i++) {
  (function(num){
      setTimeout(function(){
          playPitch(pitches[num*2]);
          playPitch(pitches[(num*2)+1]);
      }, eval(tempo) * (i+1)); 
  })(i);  
} 
UserUP86
  • 3
  • 2
  • One audio element can only play one sound at a time. Either create new element every time around should play or create a few and use the ones that are not playing currently – Konrad Oct 24 '22 at 00:01
  • Use the Web Audio API and its AudioBuffer objects. See https://stackoverflow.com/questions/30433667/cloning-audio-source-without-having-to-download-it-again/30440830 – Kaiido Oct 24 '22 at 01:41

0 Answers0