In Java, How do you stop a previous audio file when another audio file starts using key_events

前端 未结 1 410
悲哀的现实
悲哀的现实 2021-01-27 02:33

I know about the clip.stop() method, however it doesn\'t seem to work within when I have it inside the key_events. It just causes an Error. Well I know why it causes the error.

相关标签:
1条回答
  • 2021-01-27 02:59

    It's difficult to be 100% sure, but it looks like you are shadowing your variables...

    clip.stop();
    
    sample = AudioSystem.getAudioInputStream(getURL(filename));
    
    //create a sound buffer
    Clip clip = AudioSystem.getClip();
    

    In fact, I'm not even sure how this would compile...

    Define Clip as an instance variable, when you program is initialised, initialise the Clip at the same time.

    You should be able to call stop at any time, but this will only reset the Clip back to the start of the current input. What you need to, also do, is close the Clip, which releases the internal resources been managed by the Clip for the current input...

    KeyListeners are also notoriously troublesome and you should consider using Key Bindings as they provide you with the control to determine the focus level that the key events can be generated at, for example...

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.InputMap;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestPlayer {
    
        public static void main(String[] args) {
            new TestPlayer();
        }
    
        public TestPlayer() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    try {
                        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);
                    } catch (LineUnavailableException exp) {
                        exp.printStackTrace();
                    }
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private Clip clip;
            private List<File> playList;
            private int index;
    
            private JLabel label;
    
            public TestPane() throws LineUnavailableException {
                label = new JLabel("Play stuff");
                add(label);
                clip = AudioSystem.getClip();
    
                File[] files = new File("A folder of music files").listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File file) {
                        return file.getName().toLowerCase().endsWith(".wav");
                    }
                });
                playList = new ArrayList<>(Arrays.asList(files));
                index = -1;
    
                InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "previous");
                im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "next");
    
                ActionMap am = getActionMap();
                am.put("next", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        playNext();
                    }
                });
                am.put("previous", new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        playPrevious();
                    }
                });
            }
    
            public void playNext() {
                index++;
                if (index >= playList.size()) {
                    index = 0;
                }
    
                File file = playList.get(index);
    
                play(file);
            }
    
            public void playPrevious() {
                index--;
                if (index < 0) {
                    index = playList.size() - 1;
                }
    
                File file = playList.get(index);
    
                play(file);
            }
    
            public void play(File file) {
    
                try {
                    stop();
                    label.setText(file.getName());
                    AudioInputStream sample = AudioSystem.getAudioInputStream(file);
                    clip.open(sample);
                    clip.start();
                } catch (UnsupportedAudioFileException | IOException | LineUnavailableException exp) {
                    exp.printStackTrace();
                }
            }
    
            public void stop() {
    
                clip.stop();
                clip.close();
    
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题