how to have fade in/out on audio HTML5

前端 未结 1 727
眼角桃花
眼角桃花 2021-01-15 19:11

I am creating a simple background music which has only one button to play and stop the music. But I would like to add fade to it. But does not work.

My code:

相关标签:
1条回答
  • 2021-01-15 19:23

    You have to watch out for the difference between the HTMLAudioElement ($('#musicBeat')[0]) and the jQuery Object ($('#musicBeat')).

    play is a method of the HTMLAudioElement, so you'll have to access it over that (as you did), but .animate is a jQuery method and can only be called on a jQuery object.

    And you have to specify newVolume (can't leave it empty).

    var beepTwo = $("#musicBeat");
    beepTwo[0].play();
    
    $("#dan").click(function() {  
        if (beepTwo[0].paused == false) {
            beepTwo.animate({volume: 0}, 2000, 'swing', function() {
                // really stop the music 
                beepTwo[0].pause();   
            });
         } else {
             beepTwo[0].play();  
             beepTwo.animate({volume: 1}, 2000);
         }
    });
    
    0 讨论(0)
提交回复
热议问题