werner
November 14, 2020, 10:40pm
1
Hi!
regarding my last post
I’ve also posted this code on the reddit Anki community. It might be worth checking if someone came up with amendments.
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!
hkr
November 15, 2020, 12:44pm
2
[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 collection.media
folder, you can play the file with the following code:
var audioElement = new Audio('_hello.mp3');
audioElement.play();
3 Likes
werner
November 15, 2020, 2:05pm
3
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>' : '')