<!-- Buttons to control audio playback -->
<button onclick = "playAudio()" > Play Audio < /button>
<button onclick = "pauseAudio()" > Pause Audio < /button
Create an Audio object and provide the path to your audio file
var audio = new Audio('path/to/your/audiofile.mp3');
Function to play the audio
function playAudio() {
audio.play(); // Play the audio
}
Function to pause the audio
function pauseAudio() {
audio.pause(); // Pause the audio
}
Function to change the volume
function changeVolume(vol) {
audio.volume = vol; // Set the volume of the audio
}
Listen for the 'ended' event on the audio element
audio.addEventListener('ended', function() {
audio.currentTime = 0; // Reset audio to the beginning
audio.play(); // Play the audio again
});
EXTRA BONUS fade in and fade out
<!--Input range to adjust the volume -->
<input type = "range" min = "0" max = "1" step = "0.1" value = "1" onchange = "changeVolume(this.value)" >
Function to fade out the audio
function fadeOut() {
var fadeOutInterval = setInterval(function() {
if (audio.volume > 0) {
audio.volume -= 0.1; // Decrease volume by 0.1
} else {
clearInterval(fadeOutInterval); // Stop fading when volume reaches 0
audio.pause(); // Pause audio playback
}
}, fadeInterval);
}
Function to fade in the audio
function fadeIn() {
audio.play(); // Start audio playback
var fadeInInterval = setInterval(function() {
if (audio.volume < 1) {
audio.volume += 0.1; // Increase volume by 0.1
} else {
clearInterval(fadeInInterval); // Stop fading when volume reaches 1
}
}, fadeInterval);
}
No comments:
Post a Comment