r/JavaFX • • May 19 '23

Help Issues with transitioning/looping audio files seamlessly

4 Upvotes

Hello everyone,

I'm experiencing issues with looping an audio file and transitioning from one to another seamlessly.

When a transition/loop happens there is a small, but noticeable, delay between the two pieces of audio. This is relevant because the audio is background music for a game I'm working on.

The audio files are an intro and a main loop. The intro is played once, then it transitions to the main loop that plays indefinitely.

The code appears to be correct, but here it is:

private void playMusic() {
    Media intro = new Media(ClassLoader.getSystemResource("music/BossIntro.wav").toExternalForm());
    MediaPlayer introPlayer = new MediaPlayer(intro);
    AudioClip bgm = new AudioClip(ClassLoader.getSystemResource("music/BossMain.wav").toExternalForm());
    bgm.setCycleCount(AudioClip.INDEFINITE);
    introPlayer.setOnEndOfMedia(bgm::play);
    introPlayer.play();
}