java wav плеер, добавляющий паузу и продолжение

#java #swing #media-player #wav

#java #swing #медиаплеер #wav

Вопрос:

У меня есть этот код, который воспроизводит файлы 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();
      }
   }
}
  

Комментарии:

1. Если вы имеете дело с javax.sound.sampled.Clip вместо java.applet.AudioClip , вы получите больший контроль над клипом

Ответ №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);
    }
}
  

MusicContainer:

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

}