play .wav file from jar as resource using java

前端 未结 9 578
离开以前
离开以前 2020-11-30 10:56

I want to play a .wav file using java code which is in a jar file as resource. My code is look like this -

try {
     URL defaultSound = getClass().getResou         


        
相关标签:
9条回答
  • 2020-11-30 11:22

    like Kal wrote :

    1. InputStream is = getClass().getResourceAsStream("......");
    2. AudioInputStream ais = AudioSystem.getAudioInputStream(is);...

    I did just that and it didn't work at first but the problem of "java.io.IOException" was that I used File.separator and for some reason win 8.1 couldn't handle "\\"...

    public AudioInputStream getSound(String fileName){
        InputStream inputSound;
        AudioInputStream audioInStr;
        String fs = File.separator;
    
        try {
           absolutePath = fs +packageName+ fs +folderName+ fs +fileName;
           inputSound = getClass().getResourceAsStream(absolutePath);
    
           //if null pointer exception try unix, for some reason \\ doesn't work on win 8.1
           if(inputSound == null) {
               absolutePath = "/" + packageName + "/" + folderName + "/" + fileName;
               inputSound = getClass().getResourceAsStream(absolutePath);
           }
    
           audioInStr = AudioSystem.getAudioInputStream(new BufferedInputStream(inputSound));
           return audioInStr;
        }
    
    0 讨论(0)
  • 2020-11-30 11:23

    Change:

    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile);
    

    To:

    System.out.println("defaultSound " + defaultSound);  // check the URL!
    AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(defaultSound);
    
    0 讨论(0)
  • 2020-11-30 11:26

    this worked fine for me:

    public void playSound() {
            InputStream in;
            try {
                in = new BufferedInputStream(new FileInputStream(new File(
                        getClass().getClassLoader()
                                .getResource("com/kaito/resources/sound.wav").getPath())));
                AudioStream audioStream = new AudioStream(in);
                AudioPlayer.player.start(audioStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
提交回复
热议问题