How can I play sound in Java?

后端 未结 10 960
傲寒
傲寒 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:24

    For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().

    What worked for me was the following:

    void playSound(String soundFile) {
        File f = new File("./" + soundFile);
        AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
        Clip clip = AudioSystem.getClip();
        clip.open(audioIn);
        clip.start();
    }
    

    And I would play the sound with:

     playSound("sounds/effects/sheep1.wav");
    

    sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).

提交回复
热议问题