I'm making a project using audio.
And I need to change the value of this
const click1 = new Audio (changeAudio());
I have these radio inputs to choose from with the value I want to use:
<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>
I use this function:
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'};
}
Now. The sound selected needs to be played with a start button and if I have changed the selector just clicking sounds has to change without stopping playing. I couldn't make it.
I need some help here.
Thanks.
You can try something like that. I changed a little your markup to make it more general use (and semantically accurate), and as for the script part - i added notes inside snippet.
// 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 files taken from: https://www.soundhelix.com/audio-examples