当用户按下按钮时,该程序应该进行适应性起搏器测试。第二次按下该按钮,音频停止。再次按下按钮后,程序应该从开始再次开始测试。这是我的代码:
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.net.URL;
import javax.sound.sampled.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class aMeme extends JFrame implements ActionListener{
public JButton button;
public boolean check;
public boolean audio;
public void paint(Graphics g){
if (check == true){
BufferedImage img = null;
try{
img = ImageIO.read(newFile("C:/Users/kebrobst18/Downloads/Fitnessgram.png"));
} catch (IOException e){
}
g.drawImage(img, 0, 0, this);
}
}
public void start(){
setLayout(new BorderLayout());
button=new JButton();
button.setPreferredSize(new Dimension(200, 100));
button.setText("Start/Stop");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
setSize(500,500);
setVisible(true);
audio = false;
}
public void actionPerformed(ActionEvent e){
check = true;
repaint();
try{
URL fg = new URL("http://sendeyo.com/up/8658f011a4c712b5da42f74af77729fe.wav");
Clip fitness = AudioSystem.getClip();
AudioInputStream gram = AudioSystem.getAudioInputStream(fg);
fitness.open(gram);
if (audio == false){
fitness.start();
audio = true;
} else if (audio == true){
fitness.stop();
audio = false;
}
} catch (LineUnavailableException f){
}
catch (UnsupportedAudioFileException | IOException f) {
}
}
public static void main(String args[]){
aMeme x = new aMeme();
x.start();
}
}
答案 0 :(得分:4)
您的音频对象是ActionPerformed方法的本地对象。当第二次按下该按钮时,创建全新的音频对象,并且对它们的调用停止将完全没有任何有益效果,因为您没有停止当前正在播放的音频对象。将重要的音频对象放入类的实例字段中。特别是,适应性变量需要成为实例字段。
根据我的意见,其他无关但重要的问题是:
答案 1 :(得分:1)
重播同一音频文件的简单示例:
NodeList.prototype.forEach