Play sound in Java
To play sound in Java or add a sound effect to your Java application is simple. But before we dive into that, the first step is to learn how to create a custom GUI design in your Java application.
Graphical User Interface
Create a new JFrame form
Change the layout of your JFrame form to Null Layout. After changing the layout, add a jPanel to your form from the palette. Resize to fit your jPanel to your form and also change the jPanel layout to Null Layout. Change your desired background color.
Add another jPanel, make it as your application header. Do the same thing as what you just did on your first added jPanel. Then, add two jLabel and put the first jLabel in your header and the other one at the center of your form.
Make it as your buttons, insert an icon in your jLabel to make it more engaging. When you’re done designing your GUI let’s proceed with the coding stuff.
Playing sound in your Java application
To play sound in Java or add a sound in your Java application you need a sound file with wav format.
try { File wavFile = new File("C:\Sound\sample.wav"); Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(wavFile)); clip.start(); } catch (Exception e) { System.out.println(e); }
What are Clip and AudioSystem in the code?
Clip is a data line which is a very special kind of data whose audio data can be loaded prior to playback. The AudioSystem is the entry point to the sampled audio system resources.