单击“暂停”按钮时会发出fadeOut()声音

时间:2017-10-11 18:03:54

标签: javascript html html5 audio fadeout

单击暂停按钮时如何进行声音淡出?

<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> 

然后我将其称为:

<audio id="myAudio"></audio>

<button id="idj-play-button" onclick="StartOrStop()" class="btn btn-lg"><i class="glyphicon glyphicon-play"></i>
</button>

<button id="idj-pause-button" onclick="StartOrStop()" class="btn btn-lg hide"><i class="glyphicon glyphicon-refresh"></i>
</button>

我是否需要在我的If / Else语句audie.pause()上更改某些内容?我已经尝试audie.animate({volume: 0}, 1000);,但它没有用。

感谢。

2 个答案:

答案 0 :(得分:0)

只有拥有jQuery时,

audie.animate({volume: 0}, 1000);才会起作用。

您可以进行以下更改:

if (audie.paused == false) {
    let interval = setInterval(() => {
        if (audie.volume == 0) {
             audie.pause();
             clearInterval(interval);
        }
        audie.volume -= 0.05; 
    }, 800);
}

答案 1 :(得分:0)

试试这个:

   <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/dreams.mp3",
        "sounds/oizo.mp3", ];

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

                $(audie).animate({volume: 0.9}, 0);
                audie.src = srcAudio;
                audie.play();

          }

    function Stop(audioFile) {
        var audie = document.getElementById("myAudio");

                $(audie).animate({volume: 0}, 400);

          }
</script> 

HTML:

<audio id="myAudio"></audio>

<button id="idj-play-button" onclick="Start()" class="btn btn-lg"><i class="glyphicon glyphicon-play"></i>
</button>

<button id="idj-pause-button" onclick="Stop()" class="btn btn-lg hide"><i class="glyphicon glyphicon-refresh"></i>
</button>