Input the fadeout sound when you click the pause button

Asked

Viewed 47 times

1

How can I make the sound come out in fadeOut when I click pause button?

<script>
    var sounds = [
        "sounds/royksopp.mp3",
        "sounds/9thwonder.mp3",
        "sounds/thisbeat.mp3",
        "sounds/mosdef.mp3",
        "sounds/bewater.mp3",
        "sounds/boutdre.mp3",
        "sounds/masterflash.mp3",
        "sounds/2ep.mp3",
    "sounds/drewestcoast.mp3",
        "sounds/poetry.mp3",
        "sounds/mfdoom.mp3",
        "sounds/oizo.mp3", ];

    function StartOrStop(audioFile) {
        srcAudio = sounds[Math.floor(Math.random()*sounds.length)];
        var audie = document.getElementById("myAudio");
        audie.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
        }, false);

        if (audie.paused == false) {
            audie.pause();
        } else {
            audie.src = srcAudio;
            audie.play();
        }
    }
</script> 

Thank you.

1 answer

3

You have to use the .volume within a cycle of small adjustments to simulate the effect fadeout|fadein.

An example could be joining the play|pause also, so:

const fade = (function(){
    let fading = false;
    var fadeSteps = 10;
    var fadeTime = 1000; // 1 segundo

    return function(audio, fadein){
        if (fading) return;
        fading = true;
        const initialVolume = audio.volume;

        if (fadein == true) {
            audio.volume = 0;
            audie.play();
        }
        for (var i = 0; i < fadeSteps; i++) {
            setTimeout(function(){
                if (i == fadeSteps - 1) {
                    fading = false;
                    if (fadein) {
                        audio.volume = initialVolume;
                    } else {
                        audio.volume = 0;
                        audie.pause();
                    }
                }
            }, fadeTime / fadeSteps * i);
        }
    };
})();

function StartOrStop(audioFile){
    srcAudio = sounds[Math.floor(Math.random() * sounds.length)];
    var audie = document.getElementById('myAudio');
    audie.addEventListener('ended', function(){
        this.currentTime = 0;
        this.play();
    }, false);

    if (audie.pause) audie.src = srcAudio;
    fade(audie, audie.paused); // aqui passas o audio e um Booleano (fadein true ou false)
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.