[英]How to make sure the incoming voice from Google tts have fully loaded?
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. 在低网络速度下进行测试,以正确使用JavaScript中的Google tts API,这种情况是有时读取但有时却无法读取,它可能会读取“ hi”之类的很短的文本,如何确保请求的音频已加载。
<!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: 将
type
添加到混音中,并进行演示:
In case of audio (and video) you can listen to the canplay
event: 如果是音频(和视频),则可以收听
canplay
事件:
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
. 您也可以使用
canplaythrough
代替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: Chrome似乎有问题 -完全取消了:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.