Play random sound field only

Hello,

I have a script that works fine for image fields, but when used to call out sound file fields, all the sounds play in order, rather than only the randomly selected one. Does anyone know a way to correct this?

<div class="snd" hidden>{{Sound1}}</div>
<div class="snd" hidden>{{Sound2}}</div>
<div class="snd" hidden>{{Sound3}}</div>

<script>

	{
  const fields = document.querySelectorAll(".snd");

	function randomInt(max) {
		return Math.floor(Math.random() * max);
	}		
	rand = randomInt(fields.length)

	fields[rand].hidden = false;
  }
</script>

I think the root of the problem is that your approach simply hides all but one random audio buttons, however, Anki will automatically play all the sounds even if the replay buttons are hidden.

The following script seems to work fine on my computer. It tries to work around the issue by using JS to ‘click’ on the randomly selected replay button, which in turn should prevent the automatic reproduction of all other audio files:

<div class="snd" hidden>{{Sound1}}</div>
<div class="snd" hidden>{{Sound2}}</div>
<div class="snd" hidden>{{Sound3}}</div>

<script>
	{
  const fields = document.querySelectorAll(".snd");
  const soundButtons = document.querySelectorAll(".snd .replay-button");

	function randomInt(max) {
		return Math.floor(Math.random() * max);
	}		
	rand = randomInt(fields.length)
  
    fields[rand].hidden = false;
    soundButtons[rand].click();
  }
</script>

Yup. That works on my end also. Big Thanks!!!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.