Start Playing Audio from a Timestamp

Can you make audio start playing from a timestamp?

I’m using anki to memorise lyrics. The question card tells me the song and section, I type in the lyrics for that section, and then the audio plays on the answer side, it’s been working well.

I’ve been splitting up each song’s sections using a audio editor and importing the subsequent audio files. However it would save time if I could just import the whole song and tell Anki what time to start playing it on each card.

I searched online, and messed around with the html on the cards audio field, but had no luck.

I’m not sure, but there might be an add-on for that. Alternatively, if you know javascript, you can do that by using HTML audio tag and manipulating the audio element with javascript. Here is an example:

Fields

  • audio_file
    • audio file name
    • make sure to add an underscore at the beginning of the file name so that it will not be deleted as an unused file during media check, and then put the file in the collection.media folder.
    • e.g. _your_audio_file.mp3
  • start_pos
    • set the start position (in seconds)
    • can be empty
    • e.g. 5
  • end_pos
    • set the end position (in seconds)
    • can be empty
    • e.g. 10

Template

<audio id="my-audio" controls src="{{audio_file}}"></audio>

<script>
    var startPos = parseInt('{{start_pos}}', 10);
    startPos = startPos ? startPos : 0;
    var endPos = parseInt('{{end_pos}}', 10);
    var myAudio = document.querySelector('#my-audio');
    myAudio.currentTime = startPos;
    if (endPos) {
        myAudio.addEventListener('timeupdate', () => {
            if (myAudio.currentTime > endPos) {
                myAudio.pause();
                myAudio.currentTime = startPos;
            }
        });
    } else {
        myAudio.addEventListener('ended', () => {
            myAudio.currentTime = startPos;
        });
    }
    // To enable Autoplay:
    // Requires Anki 2.1.36 beta3 or higher
    // Enable "Automatically play audio" in the deck option
    // Uncomment the next line
    // myAudio.play();
</script>

Screenshot

Note

Anki 2.1.36 beta3 or higher is required to enable autoplay for <audio> tag.

I tested this template on Anki 2.1.36 beta3 and AnkiDroid 2.14.0. I’m not sure if this works on AnkiMobile, since I don’t have an iOS device.

4 Likes

Thanks heaps, that works great!

Is this supposed to work in Anki 2.1.49+ too?
I tried it with Anki 2.1.49 (dc80804a)⁩ and unluckily it did nothing for me

The “control panel” (image) is also completely static and unresponsive, the bar does not move and I cannot click on it

I wonder if I am doing something wrong (I did uncomment the “myAudio.play();” line)

I’ve just tested and confirmed it works with Anki 2.1.49 and 2.1.51 rc2 (Qt6) on Windows 10.

2 Likes

Thank you!
My mistake was that I did not remove [sound: and ] after copy-pasting the audio file from another note