Replace src url audio location with yours make it a small mp3 not more than 500kb or max 1mb so it loads really fast. Smaller the file better the user experience dont forget.
Add class name “.playaudio” do every dom element or button or anything really want to play the audio.
When people click to those doms with class name random part of the audio will play.
you can change this setting according to your audio setup as well test that too.
const audioDuration = 36; // seconds, your full MP3 length
const segmentLength = 3; // minimum random play length
<audio id="playaudio" src="your-audio-location-name.mp3" preload="auto"></audio>
<script>
// Get the single audio element once
const audio = document.getElementById("playaudio");
// Get ALL elements with the class "playaudio"
const playBtns = document.querySelectorAll(".playaudio");
// Loop through each button and add the click listener to it
playBtns.forEach(button => {
button.addEventListener("click", () => {
const audioDuration = 36; // seconds, your full MP3 length
const segmentLength = 3; // minimum random play length
audio.volume = 0.3;
// Pick random start time
const maxStartTime = audioDuration - segmentLength;
const randomStart = Math.random() * maxStartTime;
audio.currentTime = randomStart;
audio.play();
// Stop after segmentLength seconds
setTimeout(() => {
audio.pause();
}, segmentLength * 1000);
});
});
</script>