【问题标题】:java wav player adding pause and continuejava wav播放器添加暂停并继续
【发布时间】:2018-12-01 13:31:35
【问题描述】:

我有这段代码,它可以播放文件夹中的 wav 文件并播放和停止。如何添加暂停和继续?

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

【问题讨论】:

  • 如果你处理javax.sound.sampled.Clip而不是java.applet.AudioClip,你将获得对剪辑的更大控制

标签: java swing media-player wav


【解决方案1】:

如果您使用javax.sound.sampled.Clip 和支持API 而不是java.applet.AudioClip,您将获得对音频剪辑的更多控制权,例如...

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

        }
    }

}

基本上,在播放时按下“暂停”按钮,ActionListener 会获取当前播放帧并停止剪辑,当您单击play 按钮时,ActionListener 会将剪辑设置为当前帧并继续播放

【讨论】:

    【解决方案2】:

    我认为我有一个不使用内部类的更简单的解决方案。您可以仅通过行代码创建剪辑。为了让更多人可以使用代码,我使用了 JAVA 1.6。

    这是我的课程:

    主类:

    import java.awt.EventQueue;
    
    public class MainClass {
    
        public static void main(String[] _args) {
            EventQueue.invokeLater(new LaunchingWindow());
        }
    }
    

    启动窗口:

    import java.awt.BorderLayout;
    
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    
    public class LaunchingWindow extends Thread {
    
        @Override
        public void run() {
             try {
                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
             } catch (Exception _0) {
             }
    
             JFrame frame_ = new JFrame("Testing");
             frame_.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame_.setLayout(new BorderLayout());
             frame_.add(new MusicContainer());
             frame_.pack();
             frame_.setLocationRelativeTo(null);
             frame_.setVisible(true);
        }
    }
    

    音乐容器:

    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.io.File;
    
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class MusicContainer extends JPanel {
    
        private Clip clip;
        private JTextField audioFile;
        private JButton play;
        private JButton stop;
        private int lastFrame;
    
        public MusicContainer() {
            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 PlayingMusic(this));
    
            stop.addActionListener(new StoppingMusic(this));
        }
    
        public void playMusic() {
            if (clip == null) {
                try {
                    loadClip(new File(audioFile.getText()));
                    clip.start();
                    clip.addLineListener(new MusicListener(play));
                    play.setText("||");
                } catch (Exception _0) {
                    _0.printStackTrace();
                    JOptionPane.showMessageDialog(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();
                }
    
            }
        }
    
        public void stopMusic() {
            if (clip != null) {
                lastFrame = 0;
                clip.stop();
            }
        }
    
        protected void loadClip(File _audioFile) throws Exception {
    
            AudioInputStream audioStream_ = AudioSystem.getAudioInputStream(_audioFile);
            //AudioSystem.getClip() is much easier
            clip = AudioSystem.getClip();
            clip.open(audioStream_);
    
        }
    }
    

    音乐监听器:

    import javax.sound.sampled.LineEvent;
    import javax.sound.sampled.LineListener;
    import javax.swing.JButton;
    
    public class MusicListener implements LineListener {
    
        private static final String START = "START";
        private static final String OPEN = "OPEN";
        private static final String STOP = "STOP";
        private static final String CLOSE = "CLOSE";
    
        private JButton play;
    
        public MusicListener(JButton _play) {
            play = _play;
        }
    
        @Override
        public void update(LineEvent _event) {
            String eventType_ = _event.getType().toString();
            if (eventType_.equalsIgnoreCase(START)) {
                play.setText("||");
            } else if (eventType_.equalsIgnoreCase(OPEN)) {
                System.out.println("Open");
            } else if (eventType_.equalsIgnoreCase(STOP)) {
                System.out.println("close");
                play.setText(">");
            } else if (eventType_.equalsIgnoreCase(CLOSE)) {
                play.setText(">");
            }
        }
    
    }
    

    播放音乐:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class PlayingMusic implements ActionListener {
    
        private MusicContainer container;
    
        public PlayingMusic(MusicContainer _container) {
            container = _container;
        }
    
        @Override
        public void actionPerformed(ActionEvent _e) {
            container.playMusic();
        }
    
    }
    

    停止音乐:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class StoppingMusic implements ActionListener {
    
        private MusicContainer container;
    
        public StoppingMusic(MusicContainer _container) {
            container = _container;
        }
    
        @Override
        public void actionPerformed(ActionEvent _e) {
            container.stopMusic();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多