在JavaScript中添加类和播放声音的最佳方法

时间:2017-08-30 14:18:52

标签: javascript jquery html

我正在制作一个“Simon Says”游戏,我想让div处于活动状态并在div激活的同时播放声音。然后我想删除该类并停止声音,然后转到下一个div。

到目前为止,我已经研究了如何在特定时间段内添加课程;但是,如何在相同的时间内播放声音?此功能是simonSequence()功能的一部分。感谢。

代码:

//variables
var validMov;
var min = 0, max = 4;
var boardSeq = [];
var userSeq = [];
var boardSound = {
  red: "http://www.soundjay.com/button/sounds/button-09",
  blue: "http://www.soundjay.com/button/sounds/button-7",
  yellow: "http://www.soundjay.com/button/sounds/button-10",
  green: "http://www.soundjay.com/button/sounds/button-4"
}

$(document).ready(function() {

})
//1- board plays first generating random numbrer from 0 to 3 (4)
function simonSequence() {
  var random = Math.floor(Math.randon() * (max + min));
  boardSeq.push(random);
  for(var i = 0; i < boardSeq.length; i++) {
    $("#"+boardSeq[i]).addClass("active");
    setTimeout(function() {$("#"+boardSeq[i]).removeClass("active")}, 500);
  }
}

//2- user plays repeating game sequence.

//3- compare computer sequence with user and update count/display

https://codepen.io/zentech/pen/XaYygR/

2 个答案:

答案 0 :(得分:0)

很多方法可以解决这个问题,但是这样的事情应该有效

var boardSound = [
  new Audio("http://www.soundjay.com/button/sounds/button-09"), // RED
  new Audio("http://www.soundjay.com/button/sounds/button-7"), // BLUE
  new Audio("http://www.soundjay.com/button/sounds/button-10"), // YELLOW
  new Audio("http://www.soundjay.com/button/sounds/button-4") // GREEN
]

function playSound(audio) {
  audio.play();
}

function stopSound(audio) {
  audio.pause();
  audio.currentTime = 0;
}

然后在改变类

的同一个地方使用这些功能
function simonSequence() {
  var random = Math.floor(Math.randon() * (max + min));
  boardSeq.push(random);
  for(var i = 0; i < boardSeq.length; i++) {
    $("#"+boardSeq[i]).addClass("active");
    playSound(boardSound[boardSeq[i]]);
    setTimeout(function() {
      $("#"+boardSeq[i]).removeClass("active")
      stopSound(boardSound[boardSeq[i]]);
    }, 500);
  }
}

Javascript play sound on hover. stop and reset on hoveroff

Playing audio with Javascript?

答案 1 :(得分:0)

更新

添加了请求的功能 - 独家.active类切换。

音频精灵

使用音频精灵是为浏览器游戏播放音效的最有效方式。

*我使用Audacity

以下演示已在<audio>中加载了音频精灵。每个<button>将播放音频精灵的.5秒部分。

详情在演示

中发表

演示

var taps = 0;

// Reference <audio>
var fx = document.getElementById('fx');

// Reference <form>
var main = document.forms.main

/* Register click event on form#main
|| When clicked...
*/
main.addEventListener('click', function(e) {

  // This is the clicked element
  var tgt = e.target;

  // If this clicked element is a <button>...
  if (tgt.tagName === 'BUTTON') {

    // Gather all buttons within <form> into NodeList
    var buttons = this.querySelectorAll('button');

    /* Each button will have the class .active removed
    || whether they actually have it or not.
    */
    buttons.forEach(function(btn, idx) {
      btn.classList.remove('active');
    });

    /* Now add the .active class to e.target while
    || we know no other <button> has it.
    */
    tgt.classList.add('active');

    // Pass its #ID through a switch...
    switch (tgt.id) {

      /* Each <button> will play only a .5sec clip
      || of the 2sec MP3.
      */
      case 'g':
        fx.currentTime = .03;
        fx.play();
        fx.ontimeupdate = function() {
          if (fx.currentTime >= .75) {
            fx.pause();
          }
        }

        break;
      case 'r':
        fx.currentTime = .77;
        fx.play();
        fx.ontimeupdate = function() {
          if (fx.currentTime >= 1.123) {
            fx.pause();
          }
        }
        break;
      case 'y':
        fx.currentTime = 1.124;
        fx.play();
        fx.ontimeupdate = function() {
          if (fx.currentTime >= 1.134) {
            fx.pause();
          }
        }
        break;
      case 'b':
        fx.currentTime = 1.135;
        fx.play();
        fx.ontimeupdate = function() {
          if (fx.currentTime >= 1.29) {
            fx.pause();
          }
        }
        break;
      default:
        fx.currentTime = 1.30;
        fx.play();
        fx.ontimeupdate = function() {
          if (fx.currentTime >= 1.46) {
            fx.pause();
          }
        }
        break;
    }
  }
  taps++;
  main.display.value = taps;
});
#main {
  display: flex;
  flex-flow: row wrap;
  width: 140px;
}

button {
  width: 64px;
  height: 48px;
  cursor: pointer;
  display: inline-block;
}

#g {
  background: green;
  border-top-left-radius: 60%;
  order: 1;
  transition: background .5s;
}

#g:active {
  background: lime;
  transition: background .5s;
}

#r {
  background: #d70000;
  border-top-right-radius: 60%;
  order: 2;
  transition: background .5s;
}

#r:active {
  background: #ff9b9b;
  transition: background .5s;
}

#y {
  background: #cece00;
  ;
  border-bottom-left-radius: 60%;
  order: 3;
  transition: background .5s;
}

#y:active {
  background: #ff0;
  transition: background .5s;
}

#b {
  background: blue;
  border-bottom-right-radius: 60%;
  order: 4;
  transition: background .5s;
}

#b:active {
  background: cyan;
  transition: background .5s;
}
<audio id='fx' src="http://vocaroo.com/media_command.php?media=s0bN4tNnQYSn&command=download_mp3" controls></audio>


<form id='main'>
  <button id='g' type='button'>&nbsp;</button>
  <button id='r' type='button'>&nbsp;</button>

  <button id='y' type='button'>&nbsp;</button>
  <button id='b' type='button'>&nbsp;</button>
</form>
<output id='display' form='main'>0</output>