gpt4 book ai didi

java - 音乐播放器 "file not found"异常?

转载 作者:行者123 更新时间:2023-12-02 00:06:08 25 4
gpt4 key购买 nike

我正在尝试向一个简单的小java游戏添加配乐,并且我已经研究了如何做到这一点,直到我有可编译的代码。但是,当我运行它时,我收到 FileNotFound 异常。我正在使用 Eclipse,我的 wav 文件与 .class 文件位于同一目录中。

这是我的异常(exception):

java.io.FileNotFoundException: bach.wav (No such file or directory)

还有我的音乐播放器代码:

public static void play()
{
try
{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("bach.wav")));
clip.start();
}
catch (Exception exc)
{
exc.printStackTrace(System.out);
}
}

最佳答案

AudioSystem.getAudioInputStream 有一个 overloaded method需要一个URL。这将根据需要使用缓冲流。由于 .wav 文件与类文件位于同一位置,因此您可以使用 getResource:

AudioSystem.getAudioInputStream(getClass().getResource("bach.wav"));

由于播放静态,您将需要:

AudioSystem.getAudioInputStream(MyClass.class.getResource("bach.wav"));

关于java - 音乐播放器 "file not found"异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13851445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com