Java脚本 - 当尝试按顺序逐个播放音频时,所有音频立即播放(通过for循环) [英] Java script -All audio plays at once when attempting to play audio one by one in a sequence (through a for loop)

查看:142
本文介绍了Java脚本 - 当尝试按顺序逐个播放音频时,所有音频立即播放(通过for循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是链接到我的项目的代码笔 https://codepen.io/RajTheSHow/pen / vZZPqZ
当您按下错误的按钮时,它应该播放序列(音频和按钮顺序按下)。但实际发生的是当您按错按钮播放所有音频和改变颜色,不执行睡眠功能。您可以在笔中看到问题。

Here is the link to code pen to my project https://codepen.io/RajTheSHow/pen/vZZPqZ when you press the wrong button it is supposed to play the sequence(with audio and button press in order).however what actually happens is when you press the wrong button it plays all the audio and changes the color at once and doesn't execute what is in the sleep function.you can see the problem in the pen.

当您按下时运行序列的功能

the function that runs the sequence when you press the wrong button is below cal is where the order is stored of the sequence.

   //plays the sequence
function callBut(){
  onr=0;
for(i=0;i<cal.length;i++){
   // or eval ("s"+cal[i])
   window["s"+cal[i]].play();

   // set the but# to Clicked Color Ccol# then after 1 sec go back to normal color
     $("[but="+cal[i]+"]").css("background",window["Ccol"+cal[i]])
 sleep(500).then(() => {
// set the button# to Standard color Scol#
    $("[but="+cal[i]+"]").css("background",window["Scol"+cal[i]])

});


}


推荐答案

<这是正确和预期的行为。
您想要实现的内容需要等待结束事件,然后才能在下一个剪辑上调用播放。
这可以通过正确处理您可以在线查看的音频事件和链接他们一次播放一个来实现,就像这样:

This is the correct and expected behaviour. What you want to achieve requires to wait for the end event and only then invoke play on the next clip. This can be achieved by properly handling the audio events you can look up online and "chaining" them playing one at a time, much like this:

var nextSound;

function playNext()
{
  var audio;

  if (nextSound >= cal.length)
  {
    return;
  }

  audio = $(window["s"+cal[nextSound++]]);
  audio.on("ended", playNext);
  audio[0].play();
}

nextSound = 0;
playNext();

这篇关于Java脚本 - 当尝试按顺序逐个播放音频时,所有音频立即播放(通过for循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆