我尝试通过音频异步读取一个句子数组;但是,在读取另一个句子之前,我希望等待当前音频的持续时间。我试图settimeout而音频持续时间,我onloadmetadata,但它不工作。我认为audio.duration只在onloadedmetadata工作。当我调试时,我在onloaded元数据中得到了正确的持续时间,其中的NaN就是我所做的。原谅我的英语
var j = 0, texte = "";
function listen(callback) {
var sentence = texte[j];
if (j < texte.length) {
j++;
} else {
j = 0;
texte = "";
return;
}
callback(sentence, listen);
}
function play (sentence, callback) {
// Play the received speech
googleTTS(sentence, 'fr', 1) // speed normal = 1 (default), slow = 0.24
.then(function (url) {
console.log(url); // https://translate.google.com/translate_tts?...
var audio = new Audio(url);
var duration;
audio.onloadedmetadata = function(){
duration = audio.duration;
}
audio.play();
setTimeout(function(){
callback(play);
}, duration);
});
}发布于 2017-11-18 19:58:03
尝试将和ended事件处理程序添加到audio对象中:
audio.addEventListener('ended', function() {
callback(play);
});
audio.play();当当前音频播放完毕时,此事件将触发。
发布于 2017-11-18 19:56:14
audio.play()可能不会暂停加载元数据。这就是为什么会有回调的原因。因此,在调用setTimeout之前不会设置持续时间。
而不是
var duration;
audio.onloadedmetadata = function(){
duration = audio.duration;
}
audio.play();
setTimeout(function(){
callback(play);
}, duration);试一试
var duration;
audio.onloadedmetadata = function(){
duration = audio.duration;
setTimeout(function(){
callback(play);
}, duration);
}
audio.play();https://stackoverflow.com/questions/47370319
复制相似问题