Java Sound API 代码示例:音频播放
以下代码使用 Java Sound API 实现了音频文件的播放功能,包括读取音频文件、设置音频格式和播放音频等操作。
package cn.tedu.bird;
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 runner = new Runnable(){
public void run() {
try {
Clip clip = AudioSystem.getClip();
clip.open(format, data, 0, length);
clip.start();
clip.drain();
clip.stop();
clip.close();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
};
new Thread(runner).start();
}
}
该代码示例中并没有通过鼠标事件监听器实现游戏开始和重新开始的操作。
原文地址: http://www.cveoy.top/t/topic/fYgs 著作权归作者所有。请勿转载和采集!