0

I want to make four game buttons to make sound using AudioContext API in JavaScript. I set the onmouseclick listener to trigger startTone() method and onmouseup to trigger stopTone() method. However as I did like the tutorial, it doesn't make sound. Here's my code:

HTML button part:

<div id="gameButtonArea">
      <button id="button1" onclick="guess(1)" onmousedown="startTone(1)" onmouseup="stopTone()"></button>
      <button id="button2" onclick="guess(2)" onmousedown="startTone(2)" onmouseup="stopTone()"></button>
      <button id="button3" onclick="guess(3)" onmousedown="startTone(3)" onmouseup="stopTone()"></button>
      <button id="button4" onclick="guess(4)" onmousedown="startTone(4)" onmouseup="stopTone()"></button>
</div>

Javascript Initialization of Sound Synthesizer:

var context = new AudioContext()
var o = context.createOscillator()
var g = context.createGain()
g.connect(context.destination)
g.gain.setValueAtTime(0,context.currentTime)
o.connect(g)
o.start(0)

JavaScript Definition of Methods:

const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2
}

function playTone(btn,len){ 
  o.frequency.value = freqMap[btn]
  g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
  tonePlaying = true
  setTimeout(function(){
    stopTone()
  },len)
}

function startTone(btn){
  if(!tonePlaying){
    o.frequency.value = freqMap[btn]
    g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
    tonePlaying = true
  }
}

function stopTone(){
    g.gain.setTargetAtTime(0,context.currentTime + 0.05,0.025)
    tonePlaying = false
}
Shawn Xu
  • 67
  • 6
  • The code is missing declarations for a) `tonePlaying`, b) `volume` and c) `guess`. A single error like that will stop the code dead in its tracks. Add the missing stuff, and it magically starts to work: https://jsfiddle.net/pz72cu9h/ –  Mar 24 '21 at 23:37
  • @ChrisG Well I declared volume and guess(button) method somewhere else, to handle the guess correctness. Maybe I need to implement tonePlaying – Shawn Xu Mar 24 '21 at 23:45
  • Sorry I found out I have declared all these items and I figured out the problem. I will explain. – Shawn Xu Mar 24 '21 at 23:57

1 Answers1

0

I solved the problem by putting the initialization of Sound Synthesizer at the end of the script file. I found an error in console: enter image description here

If initialized at the beginning like me before, it will go wrong.

Shawn Xu
  • 67
  • 6
  • End of the script or not doesn't really matter with respect to when exactly the code is executed if the respective code is inside a function. The warnings you posted look like you've tried to play a tone before a button was pressed, not as reaction to that; however that's not what your question suggests at all. Answers need to provide working code, however the question isn't even clear enough to actually answer. –  Mar 25 '21 at 08:24