-1

I'm working on a "Simon Says" game, and I would like to make a div active and play a sound for the same duration as the div is active. Then I want to remove the class and stop the sound, then move on to next div.

So far I've worked out how to add a class for a specific period of time; however, how can I play the sound for that same amount of time? This functionality is part of the simonSequence() function. Thanks.

Code:

//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

Pen:

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

freginold
  • 3,946
  • 3
  • 13
  • 28
miatech
  • 2,150
  • 8
  • 41
  • 78

2 Answers2

0

Lots of ways to structure this, but something like this should work

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;
}

Then just use those functions in the same place you change the class

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?

Steven Goodman
  • 576
  • 3
  • 15
0

Update

Added requested feature - Exclusive .active class toggle.

Audio Sprite

Using an audio sprite is the most efficient way to play sound effects for browser games.

  • You only load one MP3. The way it is with OP, not only would you need to eventually load 4 files, you'll need to change .src constantly.
  • Using the timeupdate event there's no lag because timeupdate fires once per frame with Firefox and every 250ms for Chrome.
  • Making one is simple:
    1. Get 4 short (@ .5sec) MP3 files.
    2. Use a an online service or program* to combine all 4 files into one.

*I use Audacity

The following demo has the audio sprite already loaded in an <audio>. Each <button> will play its .5sec portion of the audio sprite.

Details are commented in demo

Demo

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>
zer00ne
  • 41,936
  • 6
  • 41
  • 68