Reputation: 145
I'm creating a guitar app that plays chords when you press certain keys. I have the code that plays the audio depending on the key that you press. Right now only the A and G chords are working. But if you press the same key again or press another key, the audio will still keep playing along with the new audio. I want the current sound to stop once you lift the key being held (keyup). I was reading about Audio.pause() and currentTime = 0, but I can't figure out how to get them to work.
document.addEventListener('keydown', function(event) {
makeSound(event.key);
});
function makeSound(key) {
switch(key) {
case "a":
var a2 = new Audio('sounds/a2.wav');
a2.play();
break;
case "g":
var g2 = new Audio('sounds/g2.wav');
g2.play();
break;
}
};
body {
background: black;
font-family: sans-serif;
}
button {
font-size: 30px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Guitar</title>
</head>
<body>
<button class="chord a2">A2</button>
<button class="chord g2">G2</button>
<script src="main.js"></script>
</body>
</html>
Upvotes: 0
Views: 1485
Reputation: 20944
To pause and reset the audio you need to have a reference to the audio that is currently played. At the moment you are creating new audio players each time a key pressed, so the reference to the audio is lost.
Place your audio chords at the top of the file. We'll be using the same audio players for every keydown event. Create a variable which will hold a reference to the audio that is currently playing.
Whenever you release the key you should check the reference if it points to a chord audio player. If it does, then it should pause it, set the currentTime
to 0
and destroy the reference.
var a2 = new Audio('sounds/a2.wav');
var g2 = new Audio('sounds/g2.wav');
var currentChord = null; // Reference to know what sound is currently playing.
var keyIsPressed = false;
document.addEventListener('keydown', function(event) {
if (keyIsPressed === false) {
makeSound(event.key);
keyIsPressed = true;
}
});
document.addEventListener('keyup', function() {
stopSound(); // Stop the sound when releasing the key.
keyIsPressed = false;
});
function makeSound(key) {
switch(key) {
case "a":
currentChord = a2; // Assign to currentChord.
break;
case "g":
currentChord = g2; // Assign to currentChord.
break;
}
currentChord.play(); // Play the currentChord.
};
function stopSound() {
if (currentChord !== null) { // Check if there is a reference.
currentChord.pause(); // Pause and..
currentChord.currentTime = 0; // ..reset if there is..
currentChord = null; // ..and then destroy the reference.
}
}
Upvotes: 1