简体   繁体   English

Java声音在Windows上不起作用,但在OS X上起作用

[英]Java sound doesn't work on Windows, but work on OS X

I have problem with playing sounds in my java application. 我在Java应用程序中播放声音时遇到问题。 Sound is playing when user get message. 用户收到消息时正在播放声音。 Everything is working on OS X but on Windows it doesn't. 一切都可以在OS X上运行,但在Windows上则不能。 I put file to jar using this command: jar uf client.jar getMsgSound.wav . 我使用以下命令将文件放入jar:jar uf client.jar getMsgSound.wav。 I suppose that the problem is with find this file. 我想问题出在找这个文件上。

public String soundName = "getMsgSound.wav";

public void playSound()
{
try {
    File soundFile = new File(soundName);
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
    Clip clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();

    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    }
}

Even if it's on Mac OS, I don't think you can read a file from a jar this way. 即使它在Mac OS上,我也不认为您可以通过这种方式从jar中读取文件。 You might just happen to place the file somewhere in your project and it gets loaded. 您可能恰好将文件放在项目中的某个位置,然后将其加载。

I just tested with reading the file directly without putting it into a jar, it worked for both Mac OS and Windows. 我刚刚进行了测试,直接读取文件而不将其放入jar中,它适用于Mac OS和Windows。

So as Greg just pointed out in the comments, you should load it from the jar file using ClassLoader. 因此,正如Greg在注释中指出的那样,您应该使用ClassLoader从jar文件中加载它。

See this post for how to load resources using ClassLoader. 有关如何使用ClassLoader加载资源的信息 ,请参见这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM