Last active
January 7, 2022 04:11
-
-
Save owenroberts/27b6539ec20fea0de9b1 to your computer and use it in GitHub Desktop.
HTML5 Audio Example JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var player = document.querySelector('audio'); | |
var playBtn = document.querySelector('#play-btn'); | |
var progress = document.querySelector('#progress'); | |
var progressTotal = document.querySelector('#progress-bar').offsetWidth; | |
var volume = document.querySelector('#volume'); | |
var speed = document.querySelector('#speed'); | |
playBtn.addEventListener('click', function() { | |
if ( player.paused ) { | |
player.play(); | |
playBtn.src = 'pause.jpg'; | |
} else { | |
player.pause(); | |
playBtn.src = 'play.jpg'; | |
} | |
}); | |
//update progress using timeupdate event | |
player.addEventListener('timeupdate', function() { | |
var progressRatio = player.currentTime / player.duration; | |
progress.style.right = progressTotal - progressRatio * progressTotal + "px"; | |
}); | |
//update progress using requestAnimationFrame | |
/*function step() { | |
var progressRatio = player.currentTime / player.duration; | |
progress.style.right = progressTotal - progressRatio * progressTotal + "px"; | |
window.requestAnimationFrame( step ); | |
} | |
window.requestAnimationFrame( step ); | |
*/ | |
player.addEventListener('ended', function() { | |
playBtn.src = 'play.jpg'; | |
}); | |
volume.addEventListener('change', function() { | |
player.volume = this.value / 100; | |
}); | |
progressBar.addEventListener('click', function(ev) { | |
var ratio = ev.offsetX / progressTotal; | |
player.currentTime = ratio * player.duration; | |
}); | |
speed.addEventListener('change', function() { | |
player.playbackRate = this.value; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment