I have been looking for a long time for a code to fade the volume by scrolling the site window up and down, but I found only a beautiful code with the function 1 -> 0.
(Fade HTML5 audio (adjust volume) using jQuery (window).scroll)
I tried to juggle the values of the function, but it didn’t work out…
Please, could you advise how to set the sound distribution on the page not 1 -> 0, but 0 -> 1 -> 0 with restrictions on the top and bottom of the site page in pixels or percentages?
p.s.enter image description here
I would like to formulate this code as a spice in my ready-made website in the readymag constructor. I don’t know how to write websites from scratch right now.
<article>
<audio loop id="soundTour" src="http://brendansheehanworks.com/100/aaaa/examples/b/longdong.wav"></audio>
</article>
<script>
$(document).ready(function() {
var audioElm = $('#soundTour').get(0);
audioElm.play();
var height = $(document).height() - $(window).height();
$(window).scroll(function() {
audioElm.volume = 1 - $(window).scrollTop() / height;
console.log(audioElm.volume);
});
});
</script>
2
Answers
I have prepared this code snippet. Basically, you’ll have to get scrolled page percent and you’ll have to make if condition if the page scrolled is less and equal to 50%, in that case, you’ll calculate the volume percent and set to volume in a low to the high way. and in else condition you’ll calculate the volume percent and you’ll minus it with 1 then you’ll set the volume high to low format.
NOTE: to autoplay the audio you’ll have to change the site setting and allow sound, otherwise you won’t hear any sound, as audio won’t play automatically on page load.
Here is one possible formula:
At the beginning,
scrollTop
is0
, so you get1 - 2 * Math.abs(0.5 - 0)
which is0
.It will then increase until
scrollTop
is half of the height, and the volume will then be1
(1 - 2 * Math.abs(0.5 - 0.5)
) and then finally it will decrease untilscrollTop
is equal toheight
where you get again0
(1 - 2 * Math.abs(0.5 - 1)
)Another "smoother" formula is