Search code examples
javascripthtmlaudiovolume

turn off audio progressively on click


I have an engine song in autoplay and i want that when i click on my button the sound turn off "progressively" for get a fluid diminution of the volume and finish at 0.1 or 0.2 of the volume, someone have an idea ? This is my actual code:

<audio autoplay>
   <source src="../audio/2445.mp3">
</audio>

<button>turn off</button>

Solution

  • not sure if this is right way to do it, you could do something like:

    <audio autoplay id='aud'>
       <source src='http://upload.wikimedia.org/wikipedia/commons/5/5b/Ludwig_van_Beethoven_-_Symphonie_5_c-moll_-_1._Allegro_con_brio.ogg'>
    </audio>
    
    <button id='btn'>turn off</button>
    

    JS:

    var audio = document.getElementById('aud'), interval;
    document.getElementById('btn').onclick = turnOff;
    function turnOff(){
        if(audio && !audio.paused){
            interval = setInterval(function(){
                console.log('audio volume: ', audio.volume);
                if(!audio || audio.paused || audio.volume < 0.1){
                    clearInterval(interval);
                }else{
                    audio.volume -= .05; // change this value as per your liking
                }
            }, 200); // change this value as per your liking
        }
    }
    

    I guess a better way to do it might be with web-audio.

    Fiddle Demo