javascript - 每 0.5 秒播放一次阵列中的声音

标签 javascript jquery setinterval

我正在构建一个西蒙游戏,但我在某些点上陷入困​​境。 我有一个带有 currentSequence 的数组,其中包含来自另一个数组的随机声音。我创建了方法和属性,以便将随机声音推送到数组中并每 0.5 秒播放一次。

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var game = function() {
  this.power = 0;
  this.start = false;
  this.strict = false;
  this.level = 1;
  this.sounds = [
    "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3",
    "https://s3.amazonaws.com/freecodecamp/simonSound2.mp3",
    "https://s3.amazonaws.com/freecodecamp/simonSound3.mp3",
    "https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"
  ];
  this.wrongMatch = "https://static.mezgrman.de/downloads/wwm/falsch.mp3";
  this.currentSequence = [];
  this.playerSequence = [];

  this.addLevel = function() {
    this.level++;
  }

  this.getcurrentSequence = function() {
    var tot = this.level;
    for (var i = 0; i <= tot; i++) {
      var index = getRandomInt(0, tot);
      this.currentSequence.push(this.sounds[index]);
    }
    console.log(this.currentSequence);
  }

  this.playCurrentSequence = function() {
    for (var i = 0; i < this.currentSequence.length; i++) {
      var audio = new Audio(this.currentSequence[i]);
      audio.play();
    }
  }

  this.reset = function() {
    this.power = 0;
    this.start = false;
    this.strict = false;
    this.level = 1;
    this.currentSequence = [];
    this.playerSequence = [];
  }
}

var simon = new game();

$(document).ready(function() {
  simon.level = 4;
  simon.getcurrentSequence();
  simon.playCurrentSequence();

最后 3 行用于测试。 我想我应该使用 setInterval 但现在我陷入困境,我看不到解决方案 哪里

最佳答案

tl;博士jsFiddle

我可以看到你是新来的,所以我重写了你的代码,让你更好地了解如何编写这些东西。主要亮点:

  • 使用 ES6 - 如果您正在编写游戏,则不需要使用 10 年前的语法
  • 使用音频事件而不是超时 - 发出音频 ended播放完毕后发生的事件。在此处查看所有有用的事件:Media Events - MDN
  • 缓存创建的音频 - 创建音频后,将其放入某个数组中。您可以使用 Audio.currentTime = 0 倒带旧音频
<小时/>
class Game {
    constructor() {
        this.power = 0;
        this.start = false;
        this.strict = false;
        this.level = 1;
        /** @type {Array<string>} */
        this.sounds = [
            "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3",
            "https://s3.amazonaws.com/freecodecamp/simonSound2.mp3",
            "https://s3.amazonaws.com/freecodecamp/simonSound3.mp3",
            "https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"
        ];
        /** @type {Array<HTMLAudioElement>} cached audios so that we don't create them every time */
        this.audios = [];
        this.audios.length = this.sounds.length;
        /** @type {HTMLAudioElement} */
        this.currentAudio = null;
        /** @type {number} timeout ID returned by setTimeout*/
        this.nextSoundTimeout = -1;
        this.shouldPlaySounds = true;


    }

    startRandomSounds() {
        this.shouldPlaySounds = true;
        this.soundDone();
    }
    stopRandomSounds() {
        this.shouldPlaySounds = false;
        if (this.currentAudio) {
            this.currentAudio.pause();
        }
    }
    /**
     * Called when sound is done playing, next sound will start after that.
     */
    soundDone() {
        if (this.shouldPlaySounds) {
            const soundIndex = Math.floor(this.sounds.length*Math.random());
            /** @type {HTMLAudioElement} */
            var audio = null;
            /// Audio created alread
            if (this.audios[soundIndex] instanceof HTMLAudioElement) {
                audio = this.audios[soundIndex];
            }
            /// Audio not created so create it
            else {
                console.info("Create audio for sound ", this.sounds[soundIndex]);
                audio = new Audio(this.sounds[soundIndex]);
                /// listen when audio is done
                audio.addEventListener("ended", () => { console.info("Done playing"); this.soundDone(); });
                this.audios[soundIndex] = audio;
            }
            this.currentAudio = audio;
            audio.currentTime = 0;
            audio.play();
        }
    }

}
const game = new Game();
game.startRandomSounds();

关于javascript - 每 0.5 秒播放一次阵列中的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117568/

相关文章:

ios - 在 Swift 中每 x 分钟做一些事情

javascript:删除元素后停止setInterval

Javascript:更改 onchange 并使用此参数

javascript - 在 map 函数中使用 promise

javascript - ASP.NET 控件后面的代码未执行

javascript - Lottie 动画和悬停 : simpler way?

javascript - 在 JavaScript 中检查浏览器不活动状态

javascript - 非管理员时的 Confluence REST API 请求以 401 错误结束

javascript - 如何在javascript中对数组序列进行排序?

Php/Jquery 表单和数据表