How can I play sound in Java?

后端 未结 10 816
傲寒
傲寒 2020-11-22 04:38

I want to be able to play sound files in my program. Where should I look?

10条回答
  •  太阳男子
    2020-11-22 05:16

    I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

    private static void playSound(String sound){
        // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
        URL file = cl.getResource(sound);
        final Media media = new Media(file.toString());
        final MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();
    }
    

    Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

    static{
        JFXPanel fxPanel = new JFXPanel();
    }
    

提交回复
热议问题