它可以找到.wav文件,但是当按下JButton时它不会播放文件。我最近在这里问了一个类似的问题,关于这个相同的代码以及它如何不会停止在第二个JButton印刷机上,而是创建一个新的音频实例。善良的人建议我将变量更改为实例字段,这是我很少有的经验。我试图改变它们,但我很可能做错了。这是我的代码:
import java.net.MalformedURLException;
import java.lang.NullPointerException;
import java.lang.IllegalArgumentException;
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 static URL fg;
public static AudioInputStream gram;
public static Clip fitness;
static{
try{
URL fg = new URL ("file:c:/Users/kebrobst18/Downloads/test.wav");
Clip fitness = AudioSystem.getClip();
AudioInputStream gram = AudioSystem.getAudioInputStream(fg);
}
catch (LineUnavailableException f){
}
catch (UnsupportedAudioFileException | IOException f) {
}
}
public void paint(Graphics g){
if (check == true){
BufferedImage img = null;
try{
img = ImageIO.read(new File("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{
if (audio == false){
fitness.open();
fitness.start();
}
else if (audio == true){
fitness.stop();
audio = false;
}
}
catch (LineUnavailableException f){
}
catch(IllegalArgumentException f){
}
catch(NullPointerException f){
}
}
public static void main(String args[]){
aMeme x = new aMeme();
x.start();
}
}