62,614
社区成员
发帖
与我相关
我的任务
分享
public class Audio {
MyPanel panel;
javax.sound.sampled.Clip clip1;
java.io.File f;
boolean life = true;
//取得播放时的系统时间,以便达到预定播放时间之后采取其他操作
long start = System.currentTimeMillis();
Clip clip;
AudioInputStream inputStream;
Audio(String file, MyPanel panel) {
this.f = new java.io.File(file);
this.panel = panel;
try {
inputStream = javax.sound.sampled.AudioSystem
.getAudioInputStream(this.f);
clip = javax.sound.sampled.AudioSystem.getClip();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void play() {
try {
clip.open(inputStream);
clip.start();
inputStream.close();
inputStream = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public void loop(String file) {// 循环播放
try {
javax.sound.sampled.AudioInputStream inputStream = javax.sound.sampled.AudioSystem
.getAudioInputStream(new java.io.File(file));
clip1 = javax.sound.sampled.AudioSystem.getClip();
clip1.open(inputStream);
clip1.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception e) {
e.printStackTrace();
}
}
//sample code for file to byte[]
InputStream input = null;
try {
input = new FileInputStream("C:\\Windows\\Media\\tada.wav");
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n = 0;
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
wavBytes = output.toByteArray();//wavBytes is a cached byte[]
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//code for fire
AudioInputStream in = AudioSystem.getAudioInputStream(new ByteArrayInputStream(wavBytes));
Clip clip = AudioSystem.getClip();
clip.open(in);
clip.start();