简体   繁体   English

尝试再次按下Jbutton后停止播放wav文件,但不会停止

[英]Attempting to stop wav file from playing after pressing the Jbutton a second time, but it doesn't stop

The program is supposed to play the fitnessgram pacer test when a user presses the button. 当用户按下按钮时,该程序应该进行健身图起搏器测试。 One the button is pressed a second time, the audio stops. 第二次按下一个按钮,音频停止。 Upon pressing the button again the program should then start playing the test from the begining again. 再次按下按钮后,程序应从头开始播放测试。 Here is my code: 这是我的代码:

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();
    }
}

Your audio objects are local to the ActionPerformed method. 您的音频对象是ActionPerformed方法的本地对象。 When the button is pressed a 2nd time, completely new audio objects are created , and calling stop on them won't have any beneficial effect at all since you're not stopping the audio object that is currently playing. 第二次按下该按钮时, 会创建一个全新的音频对象 ,并且在它们上调用stop根本不会产生任何有益的效果,因为您不会停止当前正在播放的音频对象。 Make the important audio objects into instance fields of your class. 将重要的音频对象放入类的实例字段中。 In particular, the fitness variable needs to be made an instance field. 特别是,需要将适应性变量设为实例字段。


Other unrelated but important issues are as per my comments: 其他无关但重要的问题,根据我的评论:

  • Again, in the future, please improve the format of your posted code for readability 再次,将来,请改进已发布代码的格式以提高可读性
  • Don't leave your catch blocks empty, and at least print the stacktrace. 不要将catch块留空,至少要打印stacktrace。 Otherwise you're flying blind. 否则,你会失明。
  • Don't draw within a JFrame's paint method and don't leave out the super call within your painting method. 不要在JFrame的paint方法中进行绘制,也不要在您的paint方法中忽略超级调用。 Instead paint within a JPanel's paintComponent method, and call the super's paintComponent method on its first line, 取而代之的是在JPanel的paintComponent方法中进行绘制,并在其第一行中调用父级的paintComponent方法,
  • Never read in a file from within a painting method as this is unnecessary and cuts into the perceived responsiveness of your program. 切勿从绘画方法中读取文件,因为这是不必要的,并且会切入程序的感知响应能力。
  • Close resources when you're done using them. 使用完资源后,请关闭它们。

Simple example of replaying the same audio file: 重放相同音频文件的简单示例:

import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;
import java.net.URL;
import java.io.*;

class SoundTest {

  public static void main(String[] args) throws Exception {
    URL urlToSound = new URL("file:c:/java/gun1.wav");
//    URL urlToSound = new URL("file:c:/java/flyby1.wav");
    AudioInputStream ais = AudioSystem.getAudioInputStream(urlToSound);
    final Clip clip = AudioSystem.getClip();
    clip.open(ais);
    JButton button = new JButton("Bird Sounds");
    button.addActionListener( new ActionListener(){
        public void actionPerformed(ActionEvent ae) {
          clip.setFramePosition(0);
          clip.start();
        }
      } );
    JOptionPane.showMessageDialog(null, button);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM