Audio / sound file code not working in Javascript


regarding my last post

I’m trying to include the sound file in the javascript code.

    // audio file:
+'<div class="'+ [Object.keys(list[0])[4]] + '">'
			+ list[i][Object.keys(list[0])[4]] 

As soon as I provide the sound file in the the corresponding field, i.e. [sound:audio001.mp3], the javascript code is broken.

Even if I manually type the code into the script for troubleshooting:

+ 'sound file: [sound:audio001.mp3]'

If I separate the square bracket, the output shows text only but no audio.

+ 'sound file:' + '['+ 'sound:audio001.mp3]'

Does anyone know how to make sound files in javascript work?

Thank you!

[sound:blah blah blah] is replaced with a play button or stripped by executing this function before it is passed to the webview of Anki’s reviewer screen. Therefore, javascript in a card template cannot manipulate a [sound:] tag or dynamically generate a [sound:] tag, (though you can click a play button with javascript).

A possible workaround is to use HTML <audio> tag or HTMLAudioElement interface.

For example, let’s say you have _hello.mp3 in the folder, you can play the file with the following code:

var audioElement = new Audio('_hello.mp3');;

Thank you hkr!

I’ve amended the javascript code accordingly and added a ternary condition:

// audio file:
	+ (list[i][Object.keys(list[0])[4]] != undefined ? 
		'<div class="'+ [Object.keys(list[0])[4]] + '">' 
		+ '<audio controls><source src="' + list[i][Object.keys(list[0])[4]] + '" type="audio/mp3"/></audio></div>' : '')