Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

swing - java wav player adding pause and continue

I have this code which plays wav files from a folder with play and stop. How can I add pause and continue?

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import javax.swing.event.*;
 import java.applet.AudioClip;  
 import java.net.URL;  

public class JukeBox extends JFrame {
  private JComboBox musicCombo;
  private JButton stopButton, playButton;
  private AudioClip[] music;
  private AudioClip current;

  public JukeBox(String title) {
    super(title);
    getContentPane().add(new JukeBoxControls());
  }

  public static void main(String [] args) {
    JukeBox myf = new JukeBox ("WAV COMBOBOX");
    myf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myf.pack();
    myf.setVisible(true);
  }

  private class JukeBoxControls extends JPanel {
    public JukeBoxControls() {
      URL url1, url2, url3, url4, url5;
      url1 = url2 = url3 = url4 = url5 = null;

      try
      {
         url1 = new URL ("file", "localhost", "beep-01a.wav");
         url2 = new URL ("file", "localhost", "beep-02.wav");
         url3 = new URL ("file", "localhost", "beep-03.wav");
         url4 = new URL ("file", "localhost", "beep-04.wav");
         url5 = new URL ("file", "localhost", "beep-05.wav");
      }
      catch (Exception exception) {}

      music = new AudioClip[7];
      music[0] = null;
      music[1] = JApplet.newAudioClip (url1);
      music[2] = JApplet.newAudioClip (url2);
      music[3] = JApplet.newAudioClip (url3);
      music[4] = JApplet.newAudioClip (url4);
      music[5] = JApplet.newAudioClip (url5);

      JLabel titleLabel = new JLabel ("WAV COMBOBOX");
      titleLabel.setAlignmentX (Component.CENTER_ALIGNMENT);

      String[] musicNames = {"vyberte...", "sound 1",
               "sound 2", "sound 3", "sound 4",
               "sound 5"};

      musicCombo = new JComboBox (musicNames);
      musicCombo.setAlignmentX (Component.CENTER_ALIGNMENT);

      playButton = new JButton ("Play", new ImageIcon ("play.gif"));
      playButton.setBackground (Color.white);
      stopButton = new JButton ("Stop", new ImageIcon ("stop.png"));
      stopButton.setBackground (Color.white);

      JPanel buttons = new JPanel();
      buttons.setLayout (new BoxLayout (buttons, BoxLayout.X_AXIS));
      buttons.add (playButton);
      buttons.add (Box.createRigidArea (new Dimension(5,0)));
      buttons.add (stopButton);

      setPreferredSize (new Dimension (350, 200));
      setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
      add (Box.createRigidArea (new Dimension(0,5)));
      add (titleLabel);
      add (Box.createRigidArea (new Dimension(0,5)));
      add (musicCombo);
      add (Box.createRigidArea (new Dimension(0,5)));
      add (buttons);
      add (Box.createRigidArea (new Dimension(0,5)));

      musicCombo.addActionListener (new ComboListener());
      stopButton.addActionListener (new ButtonListener());
      playButton.addActionListener (new ButtonListener());

      current = null;
    }
   }

   private class ComboListener implements ActionListener {
      public void actionPerformed (ActionEvent event)
      {
         if (current != null)
            current.stop();

         current = music[musicCombo.getSelectedIndex()];
      }
   }

   private class ButtonListener implements ActionListener {
      public void actionPerformed (ActionEvent event)
      {
         if (current != null)
            current.stop();

         if (event.getSource() == playButton)
            if (current != null)
               current.play();
      }
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you were to use javax.sound.sampled.Clip and the supporting API instead of java.applet.AudioClip, you would gain much more control over the audio clip, for example...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineEvent.Type;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SimplyPlayer {

    public static void main(String[] args) {
        new SimplyPlayer();
    }

    public SimplyPlayer() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Clip clip;
        private JTextField audioFile;
        private JButton play;
        private JButton stop;
        private int lastFrame;

        public TestPane() {
            setLayout(new GridBagLayout());

            audioFile = new JTextField(20);
            play = new JButton(">");
            stop = new JButton("[]");

            JPanel controls = new JPanel();
            controls.add(play);
            controls.add(stop);

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(audioFile, gbc);
            gbc.gridy++;
            add(controls, gbc);

            play.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (clip == null) {
                        try {
                            loadClip(new File(audioFile.getText()));
                            clip.start();
                            clip.addLineListener(new LineListener() {
                                @Override
                                public void update(LineEvent event) {
                                    if (event.getType().equals(Type.START)) {
                                        play.setText("||");
                                    } else if (event.getType().equals(Type.OPEN)) {
                                        System.out.println("Open");
                                    } else if (event.getType().equals(Type.STOP)) {
                                        play.setText(">");
                                    } else if (event.getType().equals(Type.CLOSE)) {
                                        play.setText(">");
                                    }
                                }
                            });
                            play.setText("||");
                        } catch (LineUnavailableException | IOException | UnsupportedAudioFileException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(TestPane.this, "Failed to load audio clip", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {

                        if (clip.isRunning()) {
                            lastFrame = clip.getFramePosition();
                            clip.stop();
                        } else {
                            if (lastFrame < clip.getFrameLength()) {
                                clip.setFramePosition(lastFrame);
                            } else {
                                clip.setFramePosition(0);
                            }
                            clip.start();
                        }

                    }
                }
            });

            stop.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (clip != null) {
                        lastFrame = 0;
                        clip.stop();
                    }
                }
            });
        }

        protected void loadClip(File audioFile) throws LineUnavailableException, IOException, UnsupportedAudioFileException {

            AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

            AudioFormat format = audioStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            this.clip = (Clip) AudioSystem.getLine(info);
            this.clip.open(audioStream);

        }
    }

}

Basically, when playing and you press the "pause" button, the ActionListener gets the current playback frame and stops the clip, when you click the play button ActionListener will set the clip to the current frame and resume playback


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...