Search code examples
javaaudiojavasound

Playing single audio file at any one time


How to play only 1 audio file at any one time?

So I've created a GUI which has multiple buttons, and to each button is attached an action listener. When the button is pressed, it will play the audio file (.wav). This works fine. The issue is that I want it to only play one file at any one time, so the sounds do not overlap, and I do not know what to do for this.

Will I need to use threading and synchronization? Any and all advice will be much appreciated.

EDIT

Declared as class variables:

String soundName;   
AudioInputStream audioInputStream;
Clip clip;

Actionlistener:

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==buttonOne){
     soundName = "messageOne.wav"; 
    }else if(e.getSource()==buttonTwo){
     soundName = "messageTwo.wav"; 
    }else if(e.getSource()==buttonThree){
     soundName = "messgaeThree.wav"; 
    }else if(e.getSource()==buttonFour){
     soundName = "messageFour.wav"; 
    }
    try {
        audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
    } catch (UnsupportedAudioFileException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        clip = AudioSystem.getClip();
    } catch (LineUnavailableException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        clip.open(audioInputStream);
    } catch (LineUnavailableException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    clip.start();
}

Solution

  • Stop the clip before reassigning it and starting a new one.

    @Override
    public void actionPerformed(ActionEvent e) {
        if (clip != null) {
            if (clip.isActive()) clip.stop();
            if (clip.isOpen()) clip.close();
        }