Playback audio or sound on scroll
Question: How to play an audio or sound on a specific frame or when animation starts?
Answer: Unfortunately this is not currently possible from withing the plugin UI. There have been a few similar feature requests to do that in the past, but we could not feel that it would work nicely with the plugin for most users. Also there are some technical challenges detailed below.
Forum post that has some attempts on this:
https://wordpress.org/support/topic/play-sound-file-on-certain-frame-of-sequence/#post-14612537
Autoplay policy article - user has to actively interact first, before being able to play any sounds.
https://developer.chrome.com/blog/autoplay/
The suggestion is to use script below and link it to playing back a sound.
But please note, that user needs to interact (click) with the site first to allow sound being played - so maybe let them click a button or something to allow for playback.
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
let lastKnownScrollPosition = 0;
let ticking = false;
let audio = new Audio('audio_file.mp3');
let isMusicPlaying=false;
let playbackPositionPx = 100; // here you need to calculate the real position you need the music to start playing.
function doSomething(scrollPos) {
// Here goes the play music logic
if (scrollPos > playbackPositionPx && isMusicPlaying === false){
audio.play();
isMusicPlaying = true;
}
}
document.addEventListener('scroll', function(e) {
lastKnownScrollPosition = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(lastKnownScrollPosition);
ticking = false;
});
ticking = true;
}
});