I'm trying to make a website that plays audio when a button is pressed using HTML/CSS but i'm not sure how to make the button play the music file when pressed. Does anybody know how to do this? I can also use some Javascript but i'm not the best at it if it's required.
Also I am aware that this question exists, but it's not a duplicate because that's asking how to do it in python and tkinter, but i'm asking how to do it with HTML/CSS/JS.
This will work best acc. to your use case.
const btn = document.getElementById("btn");
btn.onclick = () => {
// Here you will add path to local file you have
const audio = new Audio(
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
);
audio.play();
};
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="btn">Play Sound</button>
</div>
<script src="src/index.js"></script>
</body>
</html>
Yeah, JavaScript is pretty much required for this. You can use the audio element for this, something like so (codepen.io):
<button class="start-audio-btn">Click me!</button>
<!-- just some random mp3 I found -->
<audio src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" class="sound"></audio>
And then add functionality in JavaScript:
// Get the button element
const button = document.querySelector('.start-audio-btn');
// Get the audio element
const sound = document.querySelector('.sound');
// Start the audio element's playback using the `play` method when the button's clicked
button.addEventListener('click', (_) => { sound.play(); });
This would solve anything you would need dealing with audio => Play, Pause, Stop, Mute & Unmute :)
playBtn.onclick = () => audio.play()
stopBtn.onclick = () => {audio.pause(); audio.currentTime = 0;}
pauseBtn.onclick = () => audio.pause()
muteBtn.onclick = () => audio.muted = !audio.muted
<audio controls id='audio'>
<source src="yourAudioSource" type="audio/yourAudioExtension">
<!-- This text will be shown if a browser doesn't support the extension of your audio -->
Your browser does not support the audio element.
</audio>
<button id="playBtn">Play</button>
<button id="stopBtn">Stop</button>
<button id="pauseBtn">Pause</button>
<button id="muteBtn">Toggle Mute</button>