I wanted to ask again, based on the answer I got to a question I had asked before. I'm trying to make a sound effect when the buttons are clicked in my project. I saw that the sound effect that I gave direction to the buttons did not materialize. Then I concluded as I posted below. But this doesn't work quite right.
<button href="index.html" type="button" class="menu-icon" onClick="playMyAudio()" preload="auto">Play Audio</button>
<audio src="sound/Message Pop.mp3" preload="auto" id="myAudio"></audio>
<script>
const audioEl = document.getElementById("myAudio");
function playMyAudio() {
audioEl.play();
}
const buttonLinks = document.querySelectorAll("button[href]");
const delay = 75;//milliseconds
audioEl.addEventListener("canplaythrough", () => {
buttonLinks.forEach(btn => {
btn.addEventListener("click", (e) => {
setTimeout(() => {
window.location = btn.getAttribute("href")
}, audioEl.duration + delay);
})
});
});
</script>
What method can I follow for a more effective result here?
In the final version, the buttons sometimes sound and sometimes do not.
Thank you.
Here is an example that I threw together of clicking a button to play an MP3 in Javascript. I hope that this helps!
app.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sound Test</title>
</head>
<body>
<button id="soundButton">Click Me!</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.js
const soundButton = document.querySelector('#soundButton');
soundButton.addEventListener('click', function () { playSound(); });
function playSound() {
const sound = new Audio('catMeowing.mp3').play();
}