简体   繁体   中英

Playing audio on button click (No loop)

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.

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);"/>

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