Fade HTML5 audio (adjust volume) using jQuery (win

2019-05-21 16:28发布

问题:

I am attempting to make a page that uses html5 audio to loop a sound file in the background and fade out as the user scrolls down. Ideally it would also fade in as the user scrolls back up. I know I am way off, but here is what I am working with:

html:

 <html lang="en-US">
<head>
    <style>article {height:1000px; background:yellow;}</style>
</head>
<body>

<article>
    <audio loop id="soundTour" src="longdong.wav"></audio>
</article>


<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>

</body>
</html>

jQuery:

$(document).ready(function() {


var audioElm = $('#soundTour').get(0);
audioElm.play();
audioElm.volume=1;


$(window).scroll(function () { 
        //audioElm.volume=.1;
        var value = $(window).scroll("value");
        audioElm.volume = (value / 100);
});  
});

http://jsfiddle.net/8X6Wn/

Anyone want to take a stab at this? Thanks!!!

回答1:

You can use .scrollTop() to determine how far the user has scrolled:

$(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);
    });
});​

Demo: http://jsfiddle.net/8X6Wn/3/