javax.sound.sampled(推薦)支援 WAV、AIFF、AU 等非壓縮格式;MP3 需外掛 SPI(如 JLayer、Tritonus)。
public class AudioPlayer extends Thread {
private final String filePath;
public AudioPlayer(String path) { this.filePath = path; }
@Override public void run() {
try (AudioInputStream ais = AudioSystem.getAudioInputStream(new File(filePath))) {
AudioFormat fmt = ais.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, fmt);
try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
line.open(fmt);
line.start();
byte[] buf = new byte[4096];
int n;
while ((n = ais.read(buf)) != -1) line.write(buf, 0, n);
line.drain();
}
} catch (Exception e) { e.printStackTrace(); }
}
}
// 使用:new AudioPlayer("sound.wav").start();
sun.audio 簡易封裝(內部 API,不保證長期相容)public class MusicPlay {
private AudioStream as;
private ContinuousAudioDataStream loop;
public MusicPlay(URL url) {
try { as = new AudioStream(url.openStream()); } catch (IOException e) { e.printStackTrace(); }
}
public void start() { if (as != null) AudioPlayer.player.start(as); }
public void stop() { if (as != null) AudioPlayer.player.stop(as); }
public void loopStart() {
try { loop = new ContinuousAudioDataStream(as.getData()); AudioPlayer.player.start(loop); }
catch (IOException e) { e.printStackTrace(); }
}
public void loopStop() { if (loop != null) AudioPlayer.player.stop(loop); }
}
| 特性 | javax.sound.sampled | sun.audio |
|---|---|---|
| 模組 | 標準模組 java.desktop | JDK 內部 sun.* |
| 格式支援 | WAV/AIFF/AU + SPI 擴展 | 僅 AU/WAV 部分 |
| 控制精度 | 緩衝區、增益、聲像全控制 | 僅播放/停止/循環 |
| 長期相容 | 保證 | 可能移除(JDK 9+ 模組化) |
Clip,clip.setFramePosition(0); clip.start();SourceDataLine 串流播放,避免佔用大量堆記憶體Clip/SourceDataLine 非執行緒安全,單執行緒操作或加鎖Media media = new Media(new File("song.mp3").toURI().toString());
MediaPlayer player = new MediaPlayer(media);
player.setOnReady(() -> player.play());
player.setCycleCount(MediaPlayer.INDEFINITE); // 循環
// JavaFX 需獨立模組 java.media,JDK 11+ 需額外引入