audio fade on scroll

by envira

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Fade on Scroll</title>
    <style>
        body {
            height: 2000px; /* Just to create scrollable content */
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }

        .audio-player {
            position: fixed;
            top: 20px;
            left: 20px;
        }
    </style>
</head>
<body>
    <div class="audio-player">
        <audio id="background-audio" controls autoplay>
            <source src="your-audio-file.mp3" type="audio/mpeg">
            Your browser does not support the audio element.
        </audio>
    </div>

    <script src="script.js"></script>
</body>
</html>

JavaScript

document.addEventListener('DOMContentLoaded', function () {
    const audioElement = document.getElementById('background-audio');
    audioElement.volume = 0; // Start muted
    audioElement.play().then(() => {
        // Gradually increase volume to 1 over 3 seconds
        let fadeInterval = setInterval(() => {
            if (audioElement.volume < 1) {
                audioElement.volume += 0.05;
            } else {
                clearInterval(fadeInterval);
            }
        }, 200);
    }).catch(error => {
        console.log("Autoplay was prevented by the browser:", error);
    });

    const maxScroll = document.body.scrollHeight - window.innerHeight;
    
    window.addEventListener('scroll', function () {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const scrollPercentage = scrollTop / maxScroll;

        // Fade audio volume from 1 (100%) to 0 (0%)
        audioElement.volume = Math.max(1 - scrollPercentage, 0);
    });
});