Autoplay all audio on front of card, but not back?

I have a card type with two audio fields on the front that I would like to autoplay when the card is shown.

I have the same two audio fields on the back of the card. I don’t want them to auto play, but I do want to be able to click them to play if needed.

Currently I have autoplay turned off, and I have pasted the below script (from another thread) into the front field of the card. This autoplays the first audio on front but doesn’t autoplay the second.

 <script>
	var elem = document.querySelector(".soundLink, .replaybutton");
	if (elem) { 
		elem.click();
	}else{
		window.onload = function(){
			var elem = document.querySelector(".soundLink, .replaybutton");
			if (elem) { elem.click();}
		}
	}
 </script>

Can this script be edited to autoplay all audio fields on the front of the card?

Or alternatively, could I just turn the deck autoplay setting on and add some kind of script so it is ignored on the back of the cards?

Thanks for the help.

It probably just needs a for loop, which loops over all elements with the “.soundLink, .replaybutton” classes, then clicks using .click().

I don’t think that’s possible. The autoplay setting plays audio with python as far as I know, which isn’t controllable via js.

If you use the {{FrontSide}} special field on your back template, the same 2 audio fields will show and not autoplay. Field Replacements - Anki Manual

A simple loop won’t do, unfortunately, as every next click will interrupt the audio playback initiated by the previous one. A fixed delay can be added, but it’s not ideal solution, if the audio lengths vary too much. (it would be nice to have some kind of an API for that)

Also, if using the .click() with AnkiDroid, this should be taken into account as well:

2 Likes

Why use .click() anyways? Is there any advantage to just using .play() (which works fine for ankidroid and desktop)? I did help another user once set it up in Conditional Audio Playback - #27 by Anon_0000 so I do have some experience with .play().

So it should be possible to play all audios using a loop after grabing them with something like a .querySelector. The only thing that might be an issue is waiting for audio #1 to finish playing before audio #2 is played. Though I assume it should be solveable with HTMLMediaElement: ended event - Web APIs | MDN.

1 Like

Those would only work for audio files inserted as <audio> tags instead of Anki’s native [sound:...], which makes it less convenient to add and harder to manage, since one will have to rename all files, adding underscores, and manually keep track of which files in the collection are used and which ones are not.


Yeah, this kind of threads seems to converge to the same kind of solutions each time :slightly_smiling_face::Selective autoplay of audio for certain notes - #22 by Eltaurus

1 Like

Thanks! Using {{FrontSide}} works well.

1 Like