I have attempted to quickly hack together an imitation of this for Reborn, that gets used for all gym battles + plus a few others (i.e. any battle where your opponent has a line of dialogue when they send their last Pokémon out). I haven't fully tested it for all of them, but hopefully I added enough comments that you can fix/add whatever you need.
FinalMonMusic.rb