문제

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>
도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top