gpt4 book ai didi

java - 当我按下按钮时,Java Clip不会停止并继续播放.wav文件

转载 作者:行者123 更新时间:2023-12-03 01:55:28 24 4
gpt4 key购买 nike

我尝试制作一个程序来播放和停止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();
}

}

关于java - 当我按下按钮时,Java Clip不会停止并继续播放.wav文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com