简体   繁体   中英

How to achieve a smooth music transition with javascript

I want to fade from one song to another on a web page. Here is a codepen that illustrates the issue:

music transition test

I can achieve music volume fading with this code:

$("#mysong").animate({volume: 0}, 1000);

but the song switches before the fadeout is complete. I suspect this line

mysong.play();

is triggering the new song to play but if I omit that line, then the new song doesnt start up.

I tried this just before I change the source:

while (mysong.volume != 0)

but it has weird behavior. This first time you click the transition button, the music stops and eventually the next song fades in. Hitting the transition again only fades the volume and no longer changes the source.

The animate method has a complete parameter that accepts a function. This function will be called after the animation is complete. Check the documentation .

$("#mysong").animate({volume: 0}, 1000, function() {
     //Your code here.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM