0

I have 64 buttons, all with an individual audio file. Half of them I want to loop the audio when clicked, the others to just play the file once. Currently my code forces all to loop, so I am needing help to find a solution so that some loop, and some don't.

(I have edited the example to show only 3 buttons, I want Button 3 (FX) to only play once per click).

JS:

var audio = [];
var isPlaying = [];

function sound(id){
  if(isPlaying[id]){
    audio[id].pause();
    isPlaying[id] = false;
    audio[id].currentTime = 0;
  }
  else{
    audio[id].play();
    isPlaying[id] = true;
    audio[id].currentTime = 0;
  }
}

function createAudio(src,i){
  audio[i] = new Audio();
  audio[i].src = src;
  audio[i].loop = true;
  isPlaying[i] = false;
}

var mySources = ['audio/drums/1.wav','audio/bass/2.wav','audio/fx/3.wav'];

HTML:

<img class="button" src="images/button.png" onclick="sound(1);"/>
<img class="button" src="images/button.png" onclick="sound(2);"/>
<img class="button" src="images/button.png" onclick="sound(3);"/>

I understand that currently all 3 buttons are linked to the sound function which is set to loop, however im unaware how to create another function without the loop, as the loop is stated within createAudio and with this being code from elsewhere, i'm unsure on how that works.

1
  • Hi, it's you again with the similar question. Can you show how do you call your creaetAudio() function? I think it can be done within the function. Commented Jun 20, 2017 at 14:23

1 Answer 1

1

You could set whether a sound is a loop in the same function as you play it, instead of when it is created. This would also allow you to sometimes loop a certain sound and sometimes play it just once, instead of always having it be the same kind.

JS:

function sound(id, loop){
  audio[id].loop = loop;
  /* ... */
}

function createAudio(src,i){
  audio[i] = new Audio();
  audio[i].src = src;
  isPlaying[i] = false;
}

HTML:

<img class="button" src="images/button.png" onclick="sound(1, true);"/>
<img class="button" src="images/button.png" onclick="sound(2, false);"/>
<img class="button" src="images/button.png" onclick="sound(3, true);"/>
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly, thanks for your help! (However instead of true/false I just created a new function, and I did have to change it to audio[id].loop = true;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.