Question

Testing in low network speed, for a proper use of Google tts API from JavaScript, the case is that sometimes it reads and some times it's not, it may read very short text like 'hi', how to make sure the requested audio have load.

    <!DOCTYPE html>
    <html>
     <head>
       <meta charset="UTF-8">
       <title></title>
       <script>
        function playit() {
                var audio = new Audio();
                audio.src = 'http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=Okay i can read but not alwayes';
                //function(){testbeforplaying;}
                audio.play();
        }
      </script>
     </head>
     <body>
       <input type="button" value="say" onclick="playit()"/>
     </body>
    </html>
Was it helpful?

Solution

Loading audio (or video, or images) is an asynchronous operation so you need to listen to tap into the browser's callback mechanism to know when the file is ready for use.

Update

Added type to the mix, and demo:

Fiddle

In case of audio (and video) you can listen to the canplay event:

function playit() {
    var audio = new Audio();
    audio.addEventListener('canplay', function() {
        this.play();
    }, false);
    audio.type = 'audio/mpeg';
    audio.src = '...';
}

You could also use canplaythrough instead of canplay.

Optionally do this:

function playit() {
    var audio = new Audio();
    audio.preload = 'auto';
    audio.autoplay = true;
    audio.type = 'audio/mpeg';
    audio.src = '...';
}

There seem to be an issue with Chrome though - it cancels flat out:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top