In Java, How do you stop a previous audio file whe

2019-03-01 20:46发布

问题:

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. Because I'm asking it to essentially stop a clip that doesn't exist until a few lines later. But using this same logic or close to it if possible, how could I recode that so it knows to select the previous clip that was playing from a previous key_event. The functionality I'm intending for is: When F1 is pressed, a wav plays. When F2 is pressed, current wav STOPS, new wav STARTS. When F3 is pressed, current wav STOPS, new wav STARTS. Etc etc etc.

            case KeyEvent.VK_F1:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;


            case KeyEvent.VK_F2:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename2));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

            case KeyEvent.VK_F3:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename3));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

            case KeyEvent.VK_F4:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename4));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

            case KeyEvent.VK_F5:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename5));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

            case KeyEvent.VK_F6:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename6));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

            case KeyEvent.VK_F7:

                try {

                    //stop any sound
                    clip.stop();

                    sample = AudioSystem.getAudioInputStream(getURL(filename7));

                    //create a sound buffer
                    Clip clip = AudioSystem.getClip();

                    //load the audio file
                    clip.open(sample);

                    //play sample
                    clip.start();

                } catch (MalformedURLException ez) {
                } catch (IOException ez) {
                } catch (LineUnavailableException ez) {
                } catch (UnsupportedAudioFileException ez) {
                } catch (Exception ez) { }

                break;

Any help would be greatly appreciated :) Thanks

回答1:

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

        }

    }

}


标签: java audio wav