JavaFX sound: no exceptions, but no sound?

I’ve never played with JavaFX sound before but I’m not getting any results… What’s wrong with this code:


public class SoundThing {

    public void play() {
        Media sound;
        try {
            sound = new Media(SoundThing.class.getResource("/resource/sound/duck.mp3").toURI().toString());
        } catch (URISyntaxException e) {
            throw new RuntimeException();
        }
        System.out.println("playing sound");
        MediaPlayer mediaPlayer = new MediaPlayer(sound);
        mediaPlayer.play();
    }

}

I don’t get any exceptions, just no sound.

This is a super long shot, but I was having sound problems on Linux with JavaSound (not JavaFX Sound though). I got no sound at all unless all other programs that might use sound were closed (i.e. web browser), music player. Also, that was running an executable jar. That’s all I got. I’ve never used JavaFX sound, but it might be worth a shot to try. Maybe try getClass().getResource() ?

I’m paying the price for being superhacky I think. I confess my experiement is mishmash of Java2D and JavaFX…

This experiment is interesting. I made SoundThing an Application to isolate the behavior. I’ve commented out the call to the Java2D application’s main method. The interesting thing is it plays a sound. Despite putting it all on a separate thread, the sound only plays after the sleep() statement. I guess JavaFX stuff is locked on the main thread.


public class SoundThing  extends Application {

    public void play(String id) {
        new Runnable() {
            @Override
            public void run() {
                Media sound;
                try {
                    sound = new Media(SoundThing.class.getResource("/resource/sound/duck.mp3").toURI().toString());
                } catch (URISyntaxException e) {
                    throw new RuntimeException();
                }
                System.out.println("playing sound");
                MediaPlayer mediaPlayer = new MediaPlayer(sound);
                mediaPlayer.play();
            }
        }.run();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        play("");
        Thread.sleep(7000);
        //Game.main(new String[]{});
    }
}


Did you tried playing the sound (and loading it as well) inside Platform.runLater?

Yep… didn’t help.

Screw it. I’m using TinySound now.