jquery 按钮点击声音

hrysbysz  于 2023-03-29  发布在  jQuery
关注(0)|答案(4)|浏览(194)

这就是我想做的
我有30个按钮。我希望当点击每个按钮时,它会播放不同的mp3文件。像这样http://www.soundjig.com/pages/soundfx/beeps.html
我只知道如何点击1个按钮来播放1个音频文件,如下所示:

<audio id="mysoundclip" preload="auto">
   <source src="ci1.mp3"></source>
</audio>
<button type="button" class="ci">play</button>

<script type="text/javascript">
  var audio = $("#mysoundclip")[0];
      console.log(audio);
  $("button.play").click(function() {
      audio.play();
  });
</script>

我不想把所有的代码都应用到所有的按钮上-有什么方法可以快速地完成这个任务吗?
感谢您的阅读!

6kkfgxo0

6kkfgxo01#

您可以使用JavaScript提供的Audio类。
看看这个fiddle
下面是片段。

var baseUrl = "http://www.soundjay.com/button/";
var audio = ["beep-01a.mp3", "beep-02.mp3", "beep-03.mp3", "beep-04.mp3", "beep-05.mp3", "beep-06.mp3", "beep-07.mp3", "beep-08b.mp3", "beep-09.mp3"];

$('button.ci').click(function() {
  var i = $(this).attr('id').substring(1);           //get the index of button
  new Audio(baseUrl + audio[i - 1]).play();          //play corresponding audio
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="b1" type="button" class="ci">SOUND</button>
<br>
<button id="b2" type="button" class="ci">SOUND</button>
<br>
<button id="b3" type="button" class="ci">SOUND</button>
<br>
<button id="b4" type="button" class="ci">SOUND</button>
<br>
<button id="b5" type="button" class="ci">SOUND</button>
<br>
<button id="b6" type="button" class="ci">SOUND</button>
<br>
<button id="b7" type="button" class="ci">SOUND</button>
<br>
<button id="b8" type="button" class="ci">SOUND</button>
<br>
<button id="b9" type="button" class="ci">SOUND</button>
<br>
sg2wtvxw

sg2wtvxw2#

通过为每个按钮添加id,使按钮彼此不同。这将允许您通过将相同的id标记为<source>,将每个按钮与其自己的音频文件Map。示例:

<audio id="mysoundclip" preload="auto">
   <source src="ci1.mp3" id="1"></source>
</audio>
<button type="button" class="ci" id="1">play</button>

<script type="text/javascript">
  $("button.play").click(function() {
  var id = $('this').data('id');

  var audio = $('#mysoudclip #'+id)[0];
      audio.play();
  });
</script>
j2cgzkjk

j2cgzkjk3#

这是我的解决方案的基础上的线索Shrinivas Shukla和whiteletter(下).和这个代码播放两个 *wav和 *mp3文件:

<script type="text/javascript">
$('td.bb').click(function() { // add a same class to every button
    var fileName = $(this).attr('id'); //fileName as id button
    var audiot = new Audio("file/" +fileName+".mp3");
    audiot.play();
    var audiott = new Audio("file/" +fileName+".wav");
    audiott.play();
});

注意:将声音文件命名为我拥有的每个按钮的id,并为每个按钮添加相同的类-在这种情况下:“bb”

cedebl8k

cedebl8k4#

$(document).ready(function() {
  var obj = document.createElement("audio");
  obj.src = "http://commondatastorage.googleapis.com/codeskulptor-assets/week7-brrring.m4a";
  obj.volume = 0.1;
  obj.autoPlay = false;
  obj.preLoad = true;
  obj.controls = true;

  $(".playSound").click(function() {
    obj.play();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="playSound">Play</button>

相关问题