play .wav file from jar as resource using java

前端 未结 9 580
离开以前
离开以前 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;
        }
    

提交回复
热议问题