Access sound filename from script

I have cards with audio clips on them and would like to access the filename of the audio clip from a script.

I thought I could just put the field containing the clip in a div and then get its HTML content, but that doesn’t work. Anki does something more complicated than that when it renders a field that looks like [sound:xyz.mp3].

Anyone know a way to access the filename?

I haven’t tested it, so it might not be the right solution, but you could put only the filename in the field, and put [sound:{{Sound File}}] in your template (assuming the field containing the filename is called Sound File). If you want to access it from a script, you can also (assuming your script is in the template) do something like

let fileName = String.raw`{{Sound File}}`;

Don’t put something like that in an untrusted deck (as it’s the most basic example of how code injection works), but as long as your file names are reasonable (ie. they don’t contain backticks for example — if they do, it’s a problem on its own) it should work and be easier than the html div “trick”.

Thanks for the suggestion. Something weird happens when you put [sound:{{Sound File}}] in the template (at least it does for me). I have it below an ordinary {{Sound}}. When launching Anki and clicking study, I get the clip as normal (it’s set to play automatically) but only once. A play button corresponding to [sound:{{Sound File}}] does appear, but clicking it doesn’t do anything - and the same for the play button corresponding to {{Sound}}. When I go to the next card, I no longer get the clip that should play automatically. In other words the autoplay only works the first time after Anki is launched, and the play buttons never work. Is it possible that once Anki encounters [sound:{{Sound File}}] it starts looking for media files in a different directory?

Sound tags are processed outside the webview, so it is not possible to access the filenames from JavaScript.

Ok thanks. In that case I would need a separate field containing just the filename. If I have a lot of cards with a field like [sound:xyz.mp3] (where the actual filename is different for each card), is there a quick way to add a field that contains xyz.mp3?

I think you need to write a custom Python script to do that. Instead of duplicating the filenames, I recommend writing an add-on to access them.

Bizarrely this suggestion now seems to work perfectly. I will keep an eye on it but hopefully it will stay that way.