javascript - 收音机更改音频值 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'};
}
现在。选择的声音需要使用开始按钮播放,如果我更改了选择器,只需单击声音就必须更改而不停止播放。我来不及了。
我需要一些帮助。
谢谢。
解决方案
你可以试试类似的东西。我对您的标记进行了一些更改,以使其更通用(并且在语义上更准确),至于脚本部分 - 我在片段中添加了注释。
// 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>
推荐阅读
- node.js - “config.options.port”属性必须是数字类型 - ENV
- azure - 使用 Azure.Messaging.EventHub SDK 通过 Azure Functions 与 .NET Console App 处理 Azure Event Hub 事件,有什么实际区别吗?
- javascript - 更新具有特定 id 的对象的属性
- ios - SwiftUI 自定义 TabView 指示器
- python - msvcrt 功能似乎无法在游戏中按预期工作
- java - “范围内没有 file1 类型的封闭实例”内部类错误
- python - 我的 tkinter 倒计时功能的自定义参数不起作用;说它缺少必需的位置参数
- python - Django:找不到“登录”的反向。“登录”不是有效的视图函数或模式名称
- python - 比较和求和相同键的项目
- c - 如何从C中的字符串中删除一个数字