当我运行JAR时,声音不会播放,但是当我在eclipse中运行它时会发生声音。
这是我加载剪辑的地方:
public void init(){
System.out.println("grabbing Music");
String currentDir = new File("").getAbsolutePath();
name=new File(currentDir+"\\music\\").list();
clip=new Clip[name.length];
soundFile=new File[name.length];
for(int x=0;x<name.length;x++){
System.out.println(currentDir+"\\music\\"+name[x]);
try {
soundFile[x]= new File(currentDir+"\\music\\"+name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile[x]);
DataLine.Info info= new DataLine.Info(Clip.class, sound.getFormat());
clip[x] = (Clip) AudioSystem.getLine(info);
clip[x].open(sound);
clip[x].addLineListener(new LineListener(){
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
在Eclipse中运行它时没有任何错误。应该不存在无效的目录错误,所以有什么问题?
- 当jar在CMD中运行时,我没有错误。
编辑:我觉得我正在加载错误的音频,因此为什么我粘贴了用于加载文件的代码。在我的搜索中,我还没有看到有人使用File加载声音文件。不知道这是不是问题?
答案 0 :(得分:1)
我想到的第一件事是你没有将你的声音库类附加到你的jar中。
答案 1 :(得分:1)
为了运行您当前的代码,文件夹music
应该位于jar文件所在的文件夹中。
另一种解决方案是将您的music
文件夹打包在jar文件中,然后将代码更改为:
InputStream is = getClass().getResourceAsStream("/music/" + name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(is);
答案 2 :(得分:1)
怎么样 -
答案 3 :(得分:0)
文件系统很难看到罐子。 请尝试使用URL。 URL可以在jar中找到位置。这种情况发生在人们第一次尝试访问罐子中的资源时。 事情看起来很好。