通过类加载器,将音频播放。
package com.ctgu;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;
public class Sound {
byte[] data;
AudioFormat format;
int length;
public Sound(String name) throws Exception{
AudioInputStream in = AudioSystem.getAudioInputStream(getClass().getResource(name));
format = in.getFormat();
length = (int)in.getFrameLength();
data = new byte[length];
in.read(data);
in.close();
}
public void play(){
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Clip clip = AudioSystem.getClip();
clip.open(format, data, 0, length);
clip.start();
// System.out.println(new String(data,0,length));
// clip.drain();
// clip.stop();
// clip.close();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
}
ps:文件一定要放在Java包下面
|