我正处于try 使用vanilla JavaScript创建西蒙游戏的第一步.

我能够生成随机的 colored颜色 数组,然后我希望将其传递给playSequentially函数,该函数将逐个播放与每种 colored颜色 相关的音频文件.

然而,我的playSequentially功能没有按预期工作.如果声音已经被播放,它通常不会播放该声音.然而,这种行为似乎不可预测.例如,给定这个数组' purple ',' red ','我一直在阅读有关MDN的文档-查看currentTime,或重置结束属性.我问过chatGPT.但无济于事.有没有方法可以修复此代码,或者我的做法完全错误?谢谢你

let greenBtn = document.getElementById("green-button");
let redBtn = document.getElementById("red-button");
let blueBtn = document.getElementById("blue-button");
let purpleBtn = document.getElementById("purple-button");
let greenAudio = document.getElementById("green-audio");
let redAudio = document.getElementById("red-audio");
let blueAudio = document.getElementById("blue-audio");
let purpleAudio = document.getElementById("purple-audio");
let playback = document.getElementById("play");
greenBtn.addEventListener("click", () => {
  greenAudio.play();
})
redBtn.addEventListener("click", () => {
  redAudio.play();
})
blueBtn.addEventListener("click", () => {
  blueAudio.play();
})
purpleBtn.addEventListener("click", () => {
  purpleAudio.play();
})
let audioArray = [greenAudio, blueAudio, redAudio, purpleAudio];
function playAudio(audio) {
  audio.play();
}
function getAudioFromColor(color) {
  switch (color) {
    case "green":
      return greenAudio;
    case "blue":
      return blueAudio;
    case "red":
      return redAudio;
    case "purple":
      return purpleAudio;
  }
}
//create random array of colors of length n
function getRandomColorArray(n) {
  let randomColorArray = []
  let colors = ["green", "blue", "red", "purple"];
  let i = 0;
  while (i < n) {
    let index = Math.floor(Math.random() * 4);
    console.log(index)
    randomColorArray.push(colors[index]);
    i++;
  }
  return randomColorArray;
}
function playSequentially(audioColorArray) {
  let delay = 500;
  let currentAudio = getAudioFromColor(audioColorArray[0]);
  currentAudio.play();
  for (let i = 0; i < audioColorArray.length - 1; i++) {
    delay += 500;
    currentAudio = getAudioFromColor(audioColorArray[i]);
    currentAudio.onended = setTimeout(() => {
      getAudioFromColor(audioColorArray[i + 1]).play();
    }, delay);
  }
}
playback.addEventListener("click", () => {
  // let randomColorArray = getRandomColorArray(5);
  let randomColorArray = ['purple', 'red', 'blue', 'red', 'purple', 'red']
  console.log(randomColorArray)
  playSequentially(randomColorArray);
});
div {
  margin: 10px;
  /* padding: 10px; */
}
.game-btn {
  border: 1px solid black;
  border-radius: 20%;
  width: 200px;
  height: 200px;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}
.red {
  background-color: red
}
.purple {
  background-color: purple;
}
.green:hover {
  background-color: lightgreen;
}
.blue:hover {
  background-color: lightblue;
}
.red:hover {
  background-color: lightcoral
}
.purple:hover {
  background-color: plum;
}
#play {
  width: 100px;
  background-color: pink;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<title>Document</title>
<div class="container" style="max-width: 75%;">
  <div class="row justify-content-center">
    <div class=" btn" id="play"> Playback</div>
  </div>
  <div class="row justify-content-center">
    <div class="game-btn green btn" id="green-button"></div>
    <audio id="green-audio" src="./sounds/539252-Kalimba-INTIMATE-D5-01.wav"></audio>
    <div class="game-btn blue btn" id="blue-button"></div>
    <audio id="blue-audio" src="./sounds/539256-Kalimba-INTIMATE-E6-01.wav"></audio>
  </div>
  <div class="row justify-content-center">
    <div class="game-btn red btn" id="red-button"></div>
    <audio id="red-audio" src="./sounds/539257-Kalimba-INTIMATE-F4-01.wav"></audio>
    <div class="game-btn purple btn" id="purple-button"></div>
    <audio id="purple-audio" src="./sounds/539258-Kalimba-INTIMATE-F5-01.wav"></audio>
  </div>
</div>
<script src="./assignment22.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

推荐答案

当您已onend时,setminster并不是一个好方法.

此外,您还有关闭问题.

如果您不想在音符开始和消退时出现延迟,则需要修剪音符.

enter image description here

这是一种方法

const playSequentially = (audioColorArray) => {
  let index = 0; // Start from the first color
  const playNextAudio = () => {
    if (index < audioColorArray.length) {
      const audioElement = getAudioFromColor(audioColorArray[index]);
      audioElement.currentTime = 0; // Reset the audio time
      audioElement.play(); 
      audioElement.onended = () => {
        index++; // Move to the next index
        playNextAudio(); // Recursively call to play the next audio
      };
    }
  }
  playNextAudio(); // Start 
};
const colorArray = ['purple', 'red', 'blue', 'red', 'purple', 'red'];

playback.addEventListener("click", () => {
  colorArray.sort((a, b) => 0.5 - Math.random());
  console.log(colorArray)
  playSequentially(colorArray);
});

Javascript相关问答推荐

如何使用JavaScript向html元素添加样式

我不明白这个react 组件有什么问题

在时间轴完整日历中显示日期标题

布局样式在刷新时不持续

如何编辑代码FlipDown.js倒计时?

Klaro与Angular的集成

TypeScript索引签名模板限制

引用在HTMLAttributes<;HTMLDivElement>;中不可用

你怎么看啦啦队的回应?

无法访问Vue 3深度监视器中对象数组的特定对象值'

从页面到应用程序(NextJS):REST.STATUS不是一个函数

在数组中查找重叠对象并仅返回那些重叠对象

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

为什么云存储中的文件不能公开使用?

如何防止ionic 输入中的特殊字符.?

无法读取未定义的属性(正在读取合并)-react RTK

我想使用GAS和HTML将从Electron 表格中获得的信息插入到文本字段的初始值中

使用Reaction窗体挂钩注册日历组件

Next.js无法从外部本地主机获取图像

无法使用npm install安装react-dom、react和next