雖然Applet技術已淘汰,但java.applet.AudioClip介面在簡單音頻播放場景仍有參考價值。本文展示基於Applet的音樂播放器實現,涵蓋播放、循環、停止控制與線程安全。
public class MusicPlayer extends Applet implements ItemListener, ActionListener {
private AudioClip sound;
private Choice musicList;
private Button btnPlay, btnLoop, btnStop;
@Override
public void init() {
// 初始化播放列表
musicList = new Choice();
musicList.add("t.wav");
musicList.add("y.wav");
musicList.add("yd.wav");
musicList.addItemListener(this);
// 控制按鈕
btnPlay = new Button("播放");
btnLoop = new Button("連續");
btnStop = new Button("停止");
btnPlay.addActionListener(this);
btnLoop.addActionListener(this);
btnStop.addActionListener(this);
// 預載首曲
sound = getAudioClip(getCodeBase(), "t.wav");
sound.play();
}
@Override
public void itemStateChanged(ItemEvent e) {
// 切換音樂時重新載入
sound = getAudioClip(getCodeBase(), musicList.getSelectedItem());
sound.play();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnPlay) sound.play();
else if (e.getSource() == btnLoop) sound.loop();
else if (e.getSource() == btnStop) sound.stop();
}
}
play()單次、loop()循環、stop()停止getCodeBase()獲取Applet基礎路徑,配合相對路徑載入資源當代應用建議使用:
AudioClip方法本身線程安全,但UI操作需在事件分發線程執行。複雜場景下建議使用SwingUtilities.invokeLater()包裝播放邏輯。