首页 > 解决方案 > 收音机更改音频值 onClick

问题描述

我正在使用音频制作一个项目。

我需要改变这个的价值

const click1 = new Audio (changeAudio());

我有这些无线电输入可供选择,其中包含我想要使用的值:

<div class="sound-selector">
                <input type="radio" name="sound" value="Pato" id="Duck" onClick="changeAudio()" checked> 
                <label>Pato</label>
                <input type="radio" name="sound" value="Perro" id="Dog" onClick="changeAudio()" >
                <label>Perro</label>
                <input type="radio" name="sound" value="Gato" id="Cat" onClick="changeAudio()">
                <label>Gato</label>
                <input type="radio" name="sound" value="Vaca" id="Cow" onClick="changeAudio()">
                <label>Vaca</label>
            </div>

我使用这个功能:

function changeAudio() {

    if (document.getElementById('Duck').checked) {return 'url'};
    if (document.getElementById('Dog').checked) {return 'url'};
    if (document.getElementById('Cat').checked) {return 'url'};
    if (document.getElementById('Cow').checked) {return 'url'};
}

现在。选择的声音需要使用开始按钮播放,如果我更改了选择器,只需单击声音就必须更改而不停止播放。我来不及了。

我需要一些帮助。

谢谢。

标签: javascriptfunction

解决方案


你可以试试类似的东西。我对您的标记进行了一些更改,以使其更通用(并且在语义上更准确),至于脚本部分 - 我在片段中添加了注释。

// start with iteration over your inputs:
document.querySelectorAll('[name="sound"]').forEach(element => {  
  // listen to change event:
  element.addEventListener('change',function() {  
    // decide what audio to play when checkbox is checked
    switch (element.id) {
      case 'demo1':
      var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3');
      break;
      case 'demo2':
      var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3');
      break;
      case 'demo3':
      var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3');
      break;
    }
    // play 
    audio.play();          
  });
});
<fieldset class="sound-selector">
  <label>Demo1
    <input type="radio" name="sound" id="demo1" />
  </label>
  <label>Demo2
    <input type="radio" name="sound" id="demo2" />
  </label>
  <label>Demo3
    <input type="radio" name="sound" id="demo3" />
  </label>
</fieldset>

mp3 文件取自:https ://www.soundhelix.com/audio-examples


推荐阅读