本例演示如何在 Java Applet 中使用 AudioClip 類加載並播放聲音文件,通過按鈕控制播放、循環播放與停止操作。
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class PlayAudio extends Applet implements ActionListener {
AudioClip audio;
Button btExit, btOpen, btPlay, btLoop, btStop;
public void init() {
// 加載聲音文件(相對於文檔基礎 URL)
audio = getAudioClip(getDocumentBase(), "img/1.mid");
// 構建界面:FlowLayout + 三個按鈕
setLayout(new FlowLayout());
btPlay = new Button("Play");
btPlay.addActionListener(this);
btLoop = new Button("Loop");
btLoop.addActionListener(this);
btStop = new Button("Stop");
btStop.addActionListener(this);
add(btPlay); add(btLoop); add(btStop);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btPlay) play();
else if (e.getSource() == btLoop) loop();
else if (e.getSource() == btStop) stop();
}
public void play() {
if (audio != null) stop(); // 先停止再播放,避免重疊
audio.play();
}
public void loop() {
if (audio != null) audio.loop(); // 循環播放
}
public void stop() {
if (audio != null) audio.stop(); // 停止播放
}
}
getAudioClip(URL base, String path) 從指定基礎 URL 加載音頻play()(單次)、loop()(循環)、stop()(停止)ActionListener,通過 e.getSource() 區分按鈕getDocumentBase() 返回包含 Applet 的 HTML 頁面 URL,相對路徑 "img/1.mid" 需確保文件存在PlayAudio.class1.mid 放置於 Web 目錄下的 img/ 文件夾<applet code="PlayAudio.class" width="300" height="100"></applet>Applet 技術已過時(JDK 9 標記棄用,JDK 11 移除),現代 Web 音頻播放請使用 HTML5 <audio> 標籤 或 Web Audio API,具備更好兼容性與性能。