我正在制作一个艺术装置的网站,该网站展示了计算机如何与人类接触,并且在某些方面看起来像人类。为此,我需要按特定顺序发出警报。将音频附加到正在显示的特定警报。我总共会有超过5个警报,有5个wav。这是语音文件读数警报框将说的内容。
我这几个小时以来一直在研究这个问题,并且为了正确思考而感到沮丧。我根本不懂javascript,所以请,任何建议都是我所知道的。
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
var audio = new Audio('Images/hellllloooo.wav');
audio.oncanplay = function() {
audio.play();
alert("Hello?");
};
</script>
<script>
var audio = new Audio('Images/sorry.wav?.wav?.wav');
audio.oncanplay = function() {
audio.play();
alert("sorry?");
};
</script>
</body>
</html>
答案 0 :(得分:0)
对您的示例最简单的解决方案是“嵌套”两位代码,以便第二个警报等待第一个
var audio = new Audio('Images/hellllloooo.wav');
audio.oncanplay = function() {
audio.play();
alert("Hello?");
var audio2 = new Audio('Images/sorry.wav?.wav?.wav');
audio2.oncanplay = function() {
audio2.play();
alert("sorry?");
};
};
当然,这样做,嵌套变得凌乱,大约2,你想要5
所以,我建议使用Promises
function playAlert(msg, wav) {
return new Promise(function(resolve) {
var audio = new Audio(wav);
audio.addEventListener('canplay', function(e) {
audio.play();
alert(msg);
resolve();
});
});
}
playAlert("Hello?", 'Images/hellllloooo.wav')
.then(function() {
return playAlert("sorry?", 'Images/sorry.wav?.wav?.wav');
})
.then(function() {
return playAlert("another message", 'Images/another.wav');
})
.then(function() {
return playAlert("fourth message", 'Images/fourth.wav');
})
.then(function() {
return playAlert("fifth message", 'Images/fifth.wav');
});
以上现代javascript
const playAlert = (msg, wav) => new Promise(resolve => new Audio(wav).addEventListener('canplay', function(e) {
this.play();
alert(msg);
resolve();
}));
playAlert("Hello?", 'Images/hellllloooo.wav')
.then(() => playAlert("sorry?", 'Images/sorry.wav?.wav?.wav'))
.then(() => playAlert("another message", 'Images/another.wav'))
.then(() => playAlert("fourth message", 'Images/fourth.wav'))
.then(() => playAlert("fifth message", 'Images/fifth.wav'));
甚至
[
{"Hello?", 'Images/hellllloooo.wav'},
{"sorry?", 'Images/sorry.wav?.wav?.wav'},
{"another message", 'Images/another.wav'},
{"fourth message", 'Images/fourth.wav'},
{"fifth message", 'Images/fifth.wav'}
].reduce((p, {msg, wav}) => p.then(() => new Promise(resolve => new Audio(wav).addEventListener('canplay', function(e) {
this.play();
alert(msg);
resolve();
})), Promise.resolve());