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:
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.