我一直在试图为我的朋友做一个加载程序。他说,如果它播放音乐会更好,所以我试图添加音乐,它说它不起作用。它不断给我一个错误,说系统找不到指定的文件,但文件与类相同。JFrame加载音乐现在运行
static File sound;
static boolean muted = false;
static float volume = 100.0f;
static float pan = 0.0f;
static double seconds = 0.0d;
static boolean loopedForever = false;
static int loopTimes = 0;
static int loopsDone = 0;
public static void main(String[] args){
sound = new File("src/196006__corsica-s__patriceo.wav");
new Thread(play).start();
}
final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound
{
public void run()
{
try
{
// Check if the audio file is a .wav file
if (sound.getName().toLowerCase().contains(".wav"))
{
AudioInputStream stream = AudioSystem.getAudioInputStream(sound);
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED)
{
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(),
true);
stream = AudioSystem.getAudioInputStream(format, stream);
}
SourceDataLine.Info info = new DataLine.Info(
SourceDataLine.class,
stream.getFormat(),
(int) (stream.getFrameLength() * format.getFrameSize()));
SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
line.open(stream.getFormat());
line.start();
// Set Volume
FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
volume_control.setValue((float) (Math.log(volume/100.0f)/Math.log(10.0f) * 20.0f));
// Mute
BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE);
mute_control.setValue(muted);
FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN);
pan_control.setValue(pan);
long last_update = System.currentTimeMillis();
double since_last_update = (System.currentTimeMillis() - last_update)/1000.0d;
// Wait the amount of seconds set before continuing
while (since_last_update < seconds)
{
since_last_update = (System.currentTimeMillis() - last_update)/1000.0d;
}
System.out.println("Playing!");
int num_read = 0;
byte[] buf = new byte[line.getBufferSize()];
while ((num_read = stream.read(buf, 0, buf.length)) >= 0)
{
int offset = 0;
while (offset < num_read)
{
offset += line.write(buf, offset, num_read - offset);
}
}
line.drain();
line.stop();
if (loopedForever)
{
new Thread(play).start();
}
else if (loopsDone < loopTimes)
{
loopsDone++;
new Thread(play).start();
}
}
}
catch (Exception ex) {ex.printStackTrace();}
}
};
答案可能是在这里:http://stackoverflow.com/questions/16570523/getresourceasstream -returns-null –
尝试将文件移出包并移入源文件夹。如果您在加载文件时遇到麻烦,请不要粘贴太多的代码,10条相关的代码绰绰有余。 – user1803551
您有两种方式试图访问.wav文件:'sound = new File(“196006__corsica-s__patriceo.wav”);'和InputStream is = getClass()。getClassLoader()。getResourceAsStream(“196006_corsica- s_patriceo.wav“);'哪一行抛出错误? –