How to Change the Playback Speed on Anki Cards: The 7 Places I Got Stuck and the Full Code [PART 4]

This post contains a referral link.

In PART 3, I added US, UK and AU accent buttons to my Anki cards and was happy, thinking, “Now my English shadowing will really take off!” The audio now comes in automatically and is fairly long, though, and I wanted to change the playback speed. As a working adult, finding time for English after coming home from work and taking care of things at home is hard enough, so I thought I should grab every time-saver like this I can, and built it.

“1.0× is too slow. I want to listen a little faster.”

“That word again. I want to rewind 5 seconds.”

I also wanted to add speed buttons and a progress bar so I could change the speed and jump right to the point I want to hear.

There were quite a few places I got stuck before AI got it built for me, so I’m writing down the whole record. I’m sharing everything, including the code for the places I got stuck, so if you want to do the same thing, I think you can copy and paste it.

Sponsored links

I wanted to listen to my shadowing at different speeds

In PART 1 to 3, I built a system that automatically generates shadowing material and stocks it in Anki cards. It uses n8n and Edge TTS to automatically generate audio in three accents, US, UK and AU, and you can listen in that accent by pressing a button on the front of the card.

Adding Three Accent Buttons: Hearing US, UK and AU English on One Anki Card [PART 3]

I was shadowing every day with these PART 3 cards, but I had one complaint. The speed is fixed at 1.0×.

Well, right now I output the audio as is from a free TTS with an OpenAI-style API (I think there was a daily limit), so it’s natural, spoken-language speed.

With shadowing, there are parts of the audio I want to hear again, places where I can’t tell what they’re saying and want to repeat, and once I get used to it, repeating it a little faster seems good. When I pronounce along with it, I’d like to start slow and gradually speed up. But there was no way to change the speed of Anki’s default audio on the back of the card. There was no progress bar either, so even when I thought, “I want to hear that phrase again,” I had to play it from the beginning. Being able to go back just 5 seconds would make all the difference.

So what I tried to add this time:

  • Speed buttons (1.0×, 1.25×, 1.5×)
  • A progress bar (seek, -5 second rewind, time display)

I thought Claude would whip it up in no time, but for some reason I kept sinking deeper and deeper.

All seven places I got stuck

Stumbling point ①: pressing the speed buttons didn’t change the speed

First I added three speed buttons and wrote code that changes it on click, like audio.playbackRate = 1.5. The buttons showed up. I could press them. But the speed didn’t change…

The cause was variable scope. In PART 3, the audio object was held in a local variable, var aud = new Audio(url), but the click handler for the speed buttons was inside a different function, so it couldn’t reach aud.

“Oh, that’s what it was lol.” Claude noticed and tried to fix it right away, but in the process of this fix, it fell into an even bigger trap.

Stumbling point ②: writing [sound: in the script broke the JavaScript

To extract the audio file name, I put a regular expression like this in the script.

var match = val.match(/\[sound:([^\]]+)\]/);

Apparently it’s correct JavaScript. But the moment I pasted it into the Anki template, no audio played at all, and the play buttons themselves disappeared. ( ゚д゚)

Anki’s template engine searches the whole HTML (including inside <script>) for the pattern [sound: and automatically replaces it with the HTML for a replay button.

Whether you write it inside a regex literal, as the string '[sound:', or in a comment like // [sound:, it all gets replaced.

In other words, the JavaScript Claude wrote was being rewritten by Anki into nonsense HTML, which caused a syntax error and crashed the whole script.

Solution: write the string split up and join it at runtime

// Writing it directly gets replaced by Anki (NG)
// var SND_PFX = '[sound:';
// Write it split up (OK)
var SND_PFX = '[sou' + 'nd:';
function extractFn(val) {
  var i = val.indexOf(SND_PFX);
  if (i < 0) { return null; }
  var j = val.indexOf(']', i + SND_PFX.length);
  if (j < 0) { return null; }
  return val.substring(i + SND_PFX.length, j);
}

The important thing is never to write the string [sound: anywhere in an Anki template. If you don’t know this, I think you’ll stay stuck forever. You’re writing JavaScript, so it’s hard to even imagine Anki rewriting it on its own… (;´Д`A

Stumbling point ③: after restarting, the audio stopped playing

Just when I thought it was working, the audio stopped after I restarted Anki. The cause was the port number. The local HTTP server Anki uses to serve media files changes its port number every time it restarts.

Solution: use window.location.origin.

var url = window.location.origin + '/' + encodeURIComponent(fn);
var audio = new Audio(url);

Stumbling point ④: the debug div stayed at “…” and never changed

Inside Anki templates, top-level scripts are unstable, and document.getElementById sometimes returns null. The moment .textContent was called, a TypeError occurred and crashed the whole script. No error appears on the screen.

Solution: wrap all the code in an IIFE

(function() {
  var dbg = document.getElementById('debug');
  if (dbg) { dbg.textContent = 'JS is working'; }
})();

Stumbling point ⑤: AnkiConnect didn’t return a noteId

Claude didn’t know that guiCurrentCard doesn’t return a noteId, but it turned out there was no need to get it in two steps through the noteId at all. If you look directly at d.result.fields.AudioUS.value, it contains the raw string [sound:file name.mp3].

Stumbling point ⑥: a CORS problem (a slightly technical one)

I was using Content-Type: application/json in the fetch to AnkiConnect, but with this Content-Type, browsers send a preflight request first, and it can fail if AnkiConnect doesn’t handle it. Solution: use Content-Type: text/plain.

fetch('http://127.0.0.1:8765', {
  method: 'POST',
  headers: { 'Content-Type': 'text/plain' },  // ← this is the safe one
  body: '{"action":"guiCurrentCard","version":6}'
})

Stumbling point ⑦: flipping the card didn’t stop the audio

This was the last and most troublesome bug. If I flipped the card while the US audio was playing, it kept playing. Pressing a different accent button on the back made two play at the same time.

When you write {{FrontSide}} in Anki’s back template, the front HTML is embedded as is, and its script runs again too. But the back IIFE can’t access the front IIFE’s local variable aud.

Solution: keep the audio object in a global variable, window._ankiAud.

window._ankiAud = new Audio(url);
function stopAll() {
  if (window._ankiAud) {
    window._ankiAud.pause();
    window._ankiAud = null;
  }
  document.querySelectorAll('.accent-btn').forEach(function(b) {
    b.classList.remove('playing', 'paused');
  });
}

If you call stopAll() first when the back IIFE runs, the audio that was playing on the front stops too. With that, all seven stumbling points were solved!! ♪( ´▽`)

Here’s the complete code

For anyone who wants to do the same thing, here’s the tested code as is. I think you can copy and paste it.

It assumes you have AnkiConnect (an Anki add-on, ID: 2055492159) installed. The field names are assumed to be AudioUS, AudioUK and AudioAU.

Front template (front of the card)

<div style="display:none">{{AudioUS}}{{AudioUK}}{{AudioAU}}</div>
<div class="accent-btns">
  <div class="accent-btn" id="btn-us"><span class="flag">🇺🇸</span><span class="lbl">US</span></div>
  <div class="accent-btn" id="btn-uk"><span class="flag">🇬🇧</span><span class="lbl">UK</span></div>
  <div class="accent-btn" id="btn-au"><span class="flag">🇦🇺</span><span class="lbl">AU</span></div>
</div>
<div id="anki-player" style="display:none">
  <div class="prow">
    <span id="cur-time">0:00</span>
    <button id="rew-btn">⏮ -5s</button>
    <span id="tot-time">0:00</span>
  </div>
  <input type="range" id="prog-bar" value="0" min="0" max="100" step="0.1">
</div>
<div class="spd-btns">
  <button class="spd-btn" data-speed="1">1.0×</button>
  <button class="spd-btn" data-speed="1.25">1.25×</button>
  <button class="spd-btn" data-speed="1.5">1.5×</button>
</div>
<style>
.accent-btns { display:flex; gap:12px; justify-content:center; margin:14px 0 8px; }
.accent-btn { display:flex; flex-direction:column; align-items:center; gap:4px; padding:12px 20px; border:2px solid #d0d0d0; border-radius:16px; background:#f8f8f8; min-width:80px; cursor:pointer; user-select:none; transition:border-color 0.15s, background 0.15s; }
.accent-btn.playing { border-color:#4a90d9; background:#e8f0fe; }
.accent-btn.paused  { border-color:#aaa; background:#f0f0f0; opacity:0.8; }
.flag { font-size:2.2em; }
.lbl  { font-size:1em; font-weight:700; color:#444; }
#anki-player { background:#f5f8ff; border-radius:12px; padding:10px 16px; margin:6px 0 10px; }
.prow { display:flex; align-items:center; justify-content:space-between; font-size:12px; color:#666; margin-bottom:6px; }
#rew-btn { padding:3px 12px; border:1px solid #4a90d9; border-radius:99px; background:white; color:#4a90d9; font-size:12px; cursor:pointer; }
#prog-bar { width:100%; accent-color:#4a90d9; cursor:pointer; }
.spd-btns { display:flex; gap:8px; justify-content:center; margin:4px 0 12px; }
.spd-btn { padding:5px 14px; border:2px solid #4a90d9; border-radius:99px; background:white; color:#4a90d9; font-size:13px; font-weight:700; cursor:pointer; }
.spd-btn.active { background:#4a90d9; color:white; }
</style>
<script>
(function() {
  var files = {};
  var curAcc = null;
  var spd = 1.0;
  var dragging = false;
  var saved = sessionStorage.getItem('anki_spd');
  if (saved) { spd = parseFloat(saved); }
  document.querySelectorAll('.spd-btn').forEach(function(b) {
    if (parseFloat(b.dataset.speed) === spd) { b.classList.add('active'); }
  });
  var SND_PFX = '[sou' + 'nd:';
  function extractFn(val) {
    var i = val.indexOf(SND_PFX);
    if (i < 0) { return null; }
    var j = val.indexOf(']', i + SND_PFX.length);
    if (j < 0) { return null; }
    return val.substring(i + SND_PFX.length, j);
  }
  function fmt(s) {
    s = Math.floor(s || 0);
    return Math.floor(s / 60) + ':' + (s % 60 < 10 ? '0' : '') + (s % 60);
  }
  function updateProg() {
    if (dragging) { return; }
    var a = window._ankiAud;
    if (!a || !a.duration) { return; }
    var bar = document.getElementById('prog-bar');
    if (bar) { bar.value = (a.currentTime / a.duration) * 100; }
    var c = document.getElementById('cur-time');
    if (c) { c.textContent = fmt(a.currentTime); }
    var t = document.getElementById('tot-time');
    if (t) { t.textContent = fmt(a.duration); }
  }
  function stopAll() {
    if (window._ankiAud) { window._ankiAud.pause(); }
    window._ankiAud = null;
    document.querySelectorAll('.accent-btn').forEach(function(b) {
      b.classList.remove('playing');
      b.classList.remove('paused');
    });
  }
  function playAcc(acc, btn) {
    var a = window._ankiAud;
    if (acc === curAcc && a) {
      if (a.paused) {
        a.play();
        btn.classList.remove('paused');
        btn.classList.add('playing');
      } else {
        a.pause();
        btn.classList.remove('playing');
        btn.classList.add('paused');
      }
      return;
    }
    stopAll();
    var fn = files[acc];
    if (!fn) { return; }
    curAcc = acc;
    var na = new Audio(window.location.origin + '/' + encodeURIComponent(fn));
    na.playbackRate = spd;
    na.addEventListener('timeupdate', updateProg);
    na.addEventListener('loadedmetadata', updateProg);
    na.addEventListener('ended', function() { btn.classList.remove('playing'); });
    na.play();
    window._ankiAud = na;
    btn.classList.add('playing');
    var player = document.getElementById('anki-player');
    if (player) { player.style.display = ''; }
  }
  ['us', 'uk', 'au'].forEach(function(acc) {
    var btn = document.getElementById('btn-' + acc);
    if (btn) { btn.onclick = function() { playAcc(acc, btn); }; }
  });
  var bar = document.getElementById('prog-bar');
  if (bar) {
    bar.addEventListener('mousedown',  function() { dragging = true; });
    bar.addEventListener('touchstart', function() { dragging = true; });
    bar.addEventListener('mouseup',    function() { dragging = false; });
    bar.addEventListener('touchend',   function() { dragging = false; });
    bar.addEventListener('input', function() {
      var a = window._ankiAud;
      if (a && a.duration) { a.currentTime = a.duration * parseFloat(this.value) / 100; }
    });
  }
  var rew = document.getElementById('rew-btn');
  if (rew) {
    rew.onclick = function() {
      var a = window._ankiAud;
      if (!a) { return; }
      var t = a.currentTime - 5;
      a.currentTime = t < 0 ? 0 : t;
    };
  }
  document.querySelectorAll('.spd-btn').forEach(function(b) {
    b.onclick = function() {
      spd = parseFloat(b.dataset.speed);
      sessionStorage.setItem('anki_spd', String(spd));
      document.querySelectorAll('.spd-btn').forEach(function(x) { x.classList.remove('active'); });
      b.classList.add('active');
      var a = window._ankiAud;
      if (a) { a.playbackRate = spd; }
    };
  });
  fetch('http://127.0.0.1:8765', {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain' },
    body: '{"action":"guiCurrentCard","version":6}'
  }).then(function(r) { return r.json(); })
  .then(function(d) {
    if (!d.result || !d.result.fields) { return; }
    var f = d.result.fields;
    if (f.AudioUS) { files.us = extractFn(f.AudioUS.value); }
    if (f.AudioUK) { files.uk = extractFn(f.AudioUK.value); }
    if (f.AudioAU) { files.au = extractFn(f.AudioAU.value); }
  }).catch(function() {});
})();
</script>

Back template (back of the card)

{{FrontSide}}
<hr class="divider">
<div class="section"><div class="label">📝 Shadowing text</div><div class="shadow-text">{{Text}}</div></div>
<div class="section"><div class="label">🌐 Translation</div><div class="translation">{{Translation}}</div></div>
<div class="section"><div class="label">🔑 Key expressions</div>{{Expressions}}</div>
<div class="section"><div class="label">📚 Related vocabulary</div>{{Vocabulary}}</div>
<div class="section"><div class="label">🔗 Source</div><a class="source-link" href="{{URL}}">{{Title}}</a></div>

Summary

I got stuck seven times, but I managed to finish it.

The biggest takeaway was learning that “Anki’s template engine replaces every [sound: pattern, even inside scripts.” If you don’t know this, you’ll stay stuck forever on mysterious errors even though you should be writing correct JavaScript.

If you want to do the same thing, try copying and pasting the code. I think it will work if you just match the field names to your own note type.

If you’re interested, please give it a try. ♪( ´▽`)

Later: When I opened it in Anki on my phone, I noticed the audio didn’t play. I wrote about the cause and the fix, plus adding pause and stop buttons, in the update post (PART 5).

Shadowing English News with Anki: Auto-Made Cards in 3 Accents, Updated (Part 5)

🃏 I’ve also put all my Anki posts together on one page, sorted by what you need: getting started, settings, keeping it up, automation, audio and troubleshooting.

NO IMAGE

Referral link: if you sign up through it, I may receive free lesson minutes.

🐢 Once you can follow it slowly, try conversation at normal speed

Once changing the playback speed helps you catch what’s said, the next step is getting used to the speed of real conversation. In a conversation with a native tutor, you can ask about anything you didn’t catch right on the spot. On Cambly, you can talk any time, 24 hours a day, without booking. Through my referral link, you get 10 extra minutes when you buy a trial. I’ve been taking lessons on Cambly since July 2021.

Try Cambly with my referral link →

The referral program isn’t available in every region.

English expressions I learned (B2–C1)

① troubleshoot (to find the cause of a problem and fix it)

I spent a few hours trying to troubleshoot why the audio wasn’t playing at all.

A word for the whole process of identifying errors and fixing them. It has a broader meaning than “debug” and often appears in technical writing.

② under the hood (internally, behind the scenes)

Under the hood, Anki replaces certain text patterns before rendering the template.

A figure of speech for inner workings you can’t see from outside. The image is under the hood (bonnet) of a car.

③ trial and error

I finally got it working through trial and error after about two hours.

The repeated process of trying one thing and, if it fails, trying another.

Building an n8n System That Auto-Generates English Shadowing Material and Stocks It in Anki [PART 1]

☕ Enjoyed this post?

I'm a Japanese blogger who spent 8 years relearning English from scratch.
If this post helped you, a coffee would mean a lot — thank you for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT US
Suitman
An office worker in Japan who has worked in three fields: education, manufacturing and sales. I started learning English at 35 and, after 8 years of keeping at it, passed Eiken Grade Pre-1. VERSANT score: 59. I write about work tips, Excel, AI, English and cameras, all based on my own experience.