4

I'm trying to build a game that uses sound effects. I haven't dealt with the Java API before so I may be making some mistakes. That said though, the effects work great — my only problem is that I get a strange buzzing sound for maybe a second whenever my program exits.

Any idea how I might get rid of it? Right now I'm trying to kill any playing sounds just before the exit takes place with the killLoop() method, but that isn't getting me anywhere.

I'd appreciate your help!

public class Sound
{
private AudioInputStream audio;
private Clip clip;

public Sound(String location)
{
    try {
            audio = AudioSystem.getAudioInputStream(new File(location));
            clip = AudioSystem.getClip();
            clip.open(audio);
        }

        catch(UnsupportedAudioFileException uae) {
            System.out.println(uae);
        }
        catch(IOException ioe) {
            System.out.println(ioe);
        }
        catch(LineUnavailableException lua) {
            System.out.println(lua);
        }
}

public void play()
{
    clip.setFramePosition(0);
    clip.start();
}

public void loop()
{
    clip.loop(clip.LOOP_CONTINUOUSLY);
}

public void killLoop()
{
    clip.stop();
    clip.close();
}
}

public class Athenaeum
{
public static void main(String[] args) throws IOException
{
    final Game game = new Game();
    GUI athenaeumGui = new GUI(game);

    athenaeumGui.setSize(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT);
    athenaeumGui.setTitle("Athenaeum");
    athenaeumGui.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    athenaeumGui.setLocationRelativeTo(null);
    athenaeumGui.setMinimumSize(new Dimension(GUI.FRAME_WIDTH, GUI.FRAME_HEIGHT));
    athenaeumGui.buildGui();
    athenaeumGui.setVisible(true);

    athenaeumGui.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we)
        {
            game.killAudio(); // method calls Sound.killLoop()
            System.exit(0);
        }
    });
}

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sinclair
  • 91
  • 7

1 Answers1

1

In Java api, they say that the AudioInputStream class has a ".close()" method that "Closes this audio input stream and releases any system resources associated with the stream". Maybe this is something you can try.

  • vinc_ZEthing, the .close() function in a Clip is inherited from Line, and is the same one used by AudioInputStream. There is a flush() method that *might* help, though. But my first guess would be that System.exit(0) alone would be enough to shut everything down. I'm looking forward to learning the correct answer. – Phil Freihofner Jul 22 '13 at 17:25