我正在制作一个用于艺术装置的网站,该网站以某种方式展示了计算机如何与人类互动并看起来像人类。为此,我需要按特定顺序发送警报。将音频附加到所显示的特定警报。我将总共有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>
最佳答案
您的示例最简单的解决方案是“嵌套”这两位代码,以便第二个警报等待第一个警报
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());
关于javascript - 需要帮助将音频附加到警报框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49525860/