简体   繁体   English

单击按钮播放音频(无循环)

[英]Playing audio on button click (No loop)

I have 64 buttons, all with an individual audio file. 我有64个按钮,每个按钮都有一个单独的音频文件。 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). (我已将示例编辑为仅显示3个按钮,我希望按钮3(FX)每次单击只能播放一次)。

JS: 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: 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. 我知道目前所有3个按钮都链接到设置为循环的声音功能,但是我不知道如何在没有循环的情况下创建另一个功能,因为循环在createAudio声明,并且此代码来自其他地方,我不确定关于它是如何工作的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM