每隔0.5秒从阵列中播放声音

时间:2017-09-08 13:24:42

标签: 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,但现在我卡住了,我无法看到解决方案 其中

3 个答案:

答案 0 :(得分:1)

tl; dr 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();

答案 1 :(得分:0)

试试这样的功能:

  this.playCurrentSequence = function() {
    for (var i = 0; i < this.currentSequence.length; i++) {
      var audio = new Audio(this.currentSequence[i]);
      setTimeout(function(){audio.play();}, 500);  // This is the change I did.
    }
  }

答案 2 :(得分:0)

您可以使用音频结束事件,以便在上一个音频文件完成后立即触发。这将允许您增加每个级别的游戏难度并加快游戏速度并在正确的时间点击下一个音频。

this.playCurrentSequence = function(index) {
    var that = this;
    let audio = new Audio(this.currentSequence[index]);
    audio.onended = function(){
        if(that.currentSequence.length > index)
            that.playCurrentSequence(++index);
    }
    audio.play();
  }