Search code examples
javaeclipsejavafxmedia-player

How to get MediaPlayer to repeatedly play sound?


My MediaPlayer only plays the sound once. When I type audio.play() twice, it still only plays once. How do I get it to play again when I call audio.play()?

When I tried looking this up, most of the solutions were for Android. Where they recommended to use AudioFocus, however as my code is just Java and not Android that did not work.

I also tried to use "audio.stop()", in between the two .play()s. But that still did'nt change anything.

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.io.File;
    public class audio {
    public static void main(String[] args) {
    com.sun.javafx.application.PlatformImpl.startup(()->{});
    MediaPlayer audio = new MediaPlayer(
            new Media(
                new File("C:\\Users\\User\\Pictures\\Java Projects\\FlappyBird\\sfx_wing.mp3").toURI().toString()));
    audio.play();
    audio.play();
}
}

Currently, the first time I run "audio.play()", the sound correctly plays. But when I play it again, it doesn't play.


Solution

  • Use audio.seek(audio.getStartTime()); to play it again. Check the documentation if you have trouble understanding this line.