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
}