使用 JButton 播放和停止媒体

Play and Stop media using JButton

我正在创建一个简单的播放和停止按钮来让用户试听歌曲。 JButton1 是播放按钮,而 JButton3 应该是停止按钮。但是当我点击 JButton3 时,歌曲继续播放。有什么东西可以让 jButton3 正确运行吗?

public PlayMusic() {
    initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    try{
        if(evt.getSource()== jButton1){
        InputStream in = new FileInputStream(new File("C:\Users\A\Downloads\Music\I.wav"));
        AudioStream ikon = new AudioStream(in);         
        AudioPlayer.player.start(ikon);  }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null,e);}

}                                  

jButton3ActionPerformed()

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         try{   
        InputStream in = new FileInputStream(new File("C:\Users\A\Downloads\Music\I.wav"));
        AudioStream ikon = new AudioStream(in);      
        if(evt.getSource()== jButton3)
        {
        AudioPlayer.player.stop(ikon);
        }
        }catch(Exception e){
        JOptionPane.showMessageDialog(null,e);}
}            

您需要传递与您正在播放的 'AudioStream ikon' 相同的对象来停止音频。

快速修复,

public class Myplay{


public static void main(String[] args) {
    ...... YOUR CODE TO FOR UI.......
JButton btn1 = new JButton("Play");
    btn1.addActionListener(new ButtonListener());
    add(btn1); // ADD BUTTON TO JPanel
JButton btn2 = new JButton("Stop");
    btn2.addActionListener(new ButtonListener());
    add(btn2);  // ADD BUTTON TO JPanel
  }
}

}

class ButtonListener implements ActionListener {

ButtonListener() {
InputStream in = new FileInputStream(new File("C:\Users\A\Downloads\Music\I.wav"));
AudioStream ikon = new AudioStream(in);
}

  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Play")) {
      AudioPlayer.player.start(ikon);
    }
if (e.getActionCommand().equals("Stop")) {
      AudioPlayer.player.stop(ikon);
    }
  }
}

更新 我建议您执行以下操作

public PlayMusic() {
initComponents();
initAudioStream();
}

AudioStream ikon;

private void initAudioStream(){
            InputStream in = new FileInputStream(new File("C:\Users\A\Downloads\Music\I.wav"));
            ikon = new AudioStream(in);         
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    try{
        if(evt.getSource()== jButton1){

        AudioPlayer.player.start(ikon);  }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null,e);}

}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         try{   
        if(evt.getSource()== jButton3)
        {
        AudioPlayer.player.stop(ikon);
        }
        }catch(Exception e){
        JOptionPane.showMessageDialog(null,e);}
}