JSFiddle - React, Tailwind, and code Playground

by Ranganadh Paramkusam

HTML

<input type="text" id="str_read" placeholder="Enter text to read" />
<input type="button" value="Read" onclick="readOutLoud();" />
<audio src="" autoplay="true" id="audio_el"></audio>
<script>
    var idx = 0;
    var url_arr = [];
    var url = "https://ssl.gstatic.com/dictionary/static/sounds/de/0/{STRING}.mp3";
    function readOutLoud() {
        var text = document.getElementById("str_read").value;
        var text_arr = text.split(" ");
        url_arr = [];
        text_arr.forEach(function(str) {
            str = str.replace(/[^A-Za-z]/g,'');
            var new_url = url.replace('{STRING}', str.toLowerCase());
            url_arr.push(new_url);
        });
        if (url_arr.length > 0) {
            idx = 0;
            setUrlArray();
        }
    }
    window.onload = function() {
        document.getElementById("audio_el").addEventListener("pause", audioPaused, false);
        document.getElementById("audio_el").addEventListener("error", onError, false);
    }

    function setUrlArray() {
        document.getElementById("audio_el").src = url_arr[idx];
    }

    function audioPaused() {
        idx++;
        if (url_arr[idx]) setUrlArray()
    }
    function onError(){
        document.getElementById("audio_el").src = url.replace('{STRING}','unknown');
    }
</script>