楼主,你按照我这样改试试看。
import java.applet.AudioClip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class AudioPlayDemo extends JFrame implements ActionListener,
ItemListener {
private static final long serialVersionUID = 2694110572315454790L;
boolean looping = false;
String[] choics = { "我爱你.wav", "我爱你.wav" };
URL file1 = getClass().getResource(choics[0]);
URL file2 = getClass().getResource(choics[1]);
AudioClip sound1 = java.applet.Applet.newAudioClip(file1);
AudioClip sound2 = java.applet.Applet.newAudioClip(file2);
AudioClip chosenClip = sound1;
JComboBoxjcbFiles = new JComboBox (choics);
JButton playButton = new JButton("播放");
JButton loopButton = new JButton("循环播放");
JButton stopButton = new JButton("停止");
JLabel status = new JLabel("选择播放文件");
JPanel controlPanel = new JPanel();
Container container = getContentPane();
public AudioPlayDemo() {
super("声音播放程序");
jcbFiles.setSelectedIndex(0);
jcbFiles.addItemListener(this);
playButton.addActionListener(this);
loopButton.addActionListener(this);
stopButton.addActionListener(this);
stopButton.setEnabled(false); // 设置停止播放按钮不可用
controlPanel.add(playButton);
controlPanel.add(loopButton);
controlPanel.add(stopButton);
container.add(jcbFiles, BorderLayout.NORTH);
container.add(controlPanel, BorderLayout.CENTER);
container.add(status, BorderLayout.SOUTH);
setSize(300, 130);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e) {
if (jcbFiles.getSelectedIndex() == 0) {
chosenClip = sound1;
} else {
chosenClip = sound2;
}
}
public void actionPerformed(ActionEvent event) {
if (chosenClip == null) {
status.setText("声音未载入");
return;
}
Object source = event.getSource();
if (source == playButton) {
stopButton.setEnabled(true);
loopButton.setEnabled(true);
chosenClip.play();
status.setText("正在播放");
}
if (source == loopButton) {
looping = true;
chosenClip.loop();
loopButton.setEnabled(false);
stopButton.setEnabled(true);
status.setText("正在循环播放");
if (source == stopButton) {
if (looping) {
looping = false;
chosenClip.stop();
loopButton.setEnabled(true);
} else {
chosenClip.stop();
}
stopButton.setEnabled(false);
status.setText("停止播放");
}
}
}
public static void main(String s[]) {
new AudioPlayDemo();
}
}