[英]Java Clip won't stop and keep playing .wav file when i hit the button
我嘗試制作一個程序來播放和停止WAV,當我按下“播放”按鈕時,代碼可以播放WAV,但是當我按下“停止”按鈕時,則不能停止WAV;當我再次按下“播放”按鈕時,它會再次播放聲音,但是合並聲音之前,這是代碼:
public constructor(){
btnPlaySound.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
btnPlaySoundCLick();
} catch (LineUnavailableException | IOException
| UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});}
private void btnPlaySoundCLick() throws LineUnavailableException, IOException, UnsupportedAudioFileException{
File soundFile = new File(path);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
clip.stop();
}
}
});
// play the sound clip
if(btnPlaySound.getText().equals("Listen")){
btnPlaySound.setText("Stop");
clip.start();
} else if(btnPlaySound.getText().equals("Stop")) {
btnPlaySound.setText("Listen");
clip.stop();
}
}
這是我要執行的操作的小部分實現-請注意,該剪輯已全局設置,以便您可以訪問它,並且操作已移至該按鈕:
public class c extends JFrame {
String f="e-22.wav";
JButton btnPlaySound=new JButton("Listen");
Clip clip = null;
public c(){
btnPlaySound.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JButton b=(JButton)arg0.getSource();
// play the sound clip
if(b.getText().equals("Listen")){
b.setText("Stop");
btnPlaySoundCLick();
} else if(btnPlaySound.getText().equals("Stop")) {
b.setText("Listen");
clip.stop();
}
} catch (LineUnavailableException | IOException
| UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
setSize(500, 500);
add(btnPlaySound);
setVisible(true);
}
private void btnPlaySoundCLick() throws LineUnavailableException, IOException, UnsupportedAudioFileException{
File soundFile = new File(f);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile);
DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat());
clip = (Clip) AudioSystem.getLine(info);
clip.open(sound);
clip.addLineListener(new LineListener() {
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
System.out.println("stop");
event.getLine().close();
}
}
});
clip.start();
}
public static void main(String[] args) {
c cc=new c();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.