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