I have an HTML audio element playing an MP3 file, and my goal is to smoothly transition this to a different MP3 file using vanilla JS or jQuery. In other words, I’m looking to fade in the new track while the old track is still fading out. Replacing the src would instantly change the song rather than gradually crossfade them, so that wouldn’t be viable.
One solution I’ve found is using two audio elements, where one would serve as a “backup” containing the new song. When I want to transition them, I would gradually lower the volume of the current track and raise the volume of the backup:
var currentTrack = $('#currentSong')
var backupTrack = $('#newSong')
currentTrack.animate({volume: 0}, 1000) //Fade out the current song
backupTrack[0].load()
backupTrack.animate({volume: 1}, 1000) //Fade in new song
backupTrack[0].play()
While this does work, it feels a bit hacky, especially if I want to apply this to several audio elements. I’m wondering if there’s a more efficient way to do this without doubling the number of audio elements on the page.