TTS on AnkiWeb (Potential Solution)

This is a workaround I came up with, making Cards reliant on the Text-to-Speech fully functioning on AnkiWeb. It might be helpful for people looking for a solution to this thread from the past or having other similar questions in the future.

Before:


After:

To incorporate AnkiWeb TTS into a Card Template, simply copy and paste the following script:

<script>
function parseTTSAttrs(attr_string) {
    const attrs = {};
    attr_string.trim().split(/\s+/).forEach(attr => {
        const [key, value] = attr.split('=');
        if (key && value) attrs[key] = value;
    });
    return attrs;
}

function awTTS(text, lang) {
  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = lang;
  window.speechSynthesis.speak(utterance);
}

function sanitizeStr(str) {
    return str.replace(/['"]/g, "")
}

function TTS2asvg(htmlContent) {
	const TTSRegex = /\[anki:tts([^\]]*)\]([^\[]*)\[\/anki:tts\]/g;
  return htmlContent.replace(TTSRegex, (_, attr_string, word) => {
    const attrs = parseTTSAttrs(attr_string);
    const lang = attrs["lang"]?.replace('_','-') || "en-US";
    return `
      <a class="replay-button soundLink awtts" onclick="awTTS('${sanitizeStr(word)}','${sanitizeStr(lang)}')" href="../#">
        <svg class="playImage" viewBox="0 0 64 64" version="1.1" width="40px" height="40px">
          <circle cx="32" cy="32" r="29" fill="#fff" stroke="#414141"></circle>
          <path fill="#414141" d="M56.502,32.301l-37.502,20.101l0.329,-40.804l37.173,20.703Z"></path>
        </svg>
      </a>
    `;
  });
}

(()=>{
	const qaL = document.querySelector('#qa_box #qa');
	if (!qaL) return;
	qaL.innerHTML = TTS2asvg(qaL.innerHTML);
})();
</script>

The execution depends on the web browser and operating system. In particular, it won’t work on Linux without additional setup (but neither would the stock TTS in the desktop app). In most other cases, it should produce satisfactory results.
The audio buttons need to be clicked to play the TTS audio back – autoplaying audio on AnkiWeb will require a separate script.

If you try this out, please let me know how it goes.

6 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.