使用JButton播放和停止媒体

时间:2015-12-07 07:23:29

标签: java netbeans media

我正在创建一个简单的播放和停止按钮,让用户预览歌曲。 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);}
}            

1 个答案:

答案 0 :(得分:0)

您需要传递用于播放的音频流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);}
}