How to play audio in Java Application

how to play mp3 file in java netbeans
audiostream java
sun.audio java
java sound effects
java play wav file
java play audio from url
java play audio from buffer
how to add sound in java swing

I'm making a java application and I need to play audio. I'm playing mainly small sound files of my cannon firing (its a cannon shooting game) and the projectiles exploding, though I plan on having looping background music. I have found two different methods to accomplish this, but both don't work how I want.

The first method is literally a method:

        public void playSoundFile(File file) {//http://java.ittoolbox.com/groups/technical-functional/java-l/sound-in-an-application-90681

        try {
//get an AudioInputStream
            AudioInputStream ais = AudioSystem.getAudioInputStream(file);
//get the AudioFormat for the AudioInputStream
            AudioFormat audioformat = ais.getFormat();
            System.out.println("Format: " + audioformat.toString());
            System.out.println("Encoding: " + audioformat.getEncoding());
            System.out.println("SampleRate:" + audioformat.getSampleRate());
            System.out.println("SampleSizeInBits: " + audioformat.getSampleSizeInBits());
            System.out.println("Channels: " + audioformat.getChannels());
            System.out.println("FrameSize: " + audioformat.getFrameSize());
            System.out.println("FrameRate: " + audioformat.getFrameRate());
            System.out.println("BigEndian: " + audioformat.isBigEndian());
//ULAW format to PCM format conversion
            if ((audioformat.getEncoding() == AudioFormat.Encoding.ULAW)
                    || (audioformat.getEncoding() == AudioFormat.Encoding.ALAW)) {
                AudioFormat newformat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                        audioformat.getSampleRate(),
                        audioformat.getSampleSizeInBits() * 2,
                        audioformat.getChannels(),
                        audioformat.getFrameSize() * 2,
                        audioformat.getFrameRate(), true);
                ais = AudioSystem.getAudioInputStream(newformat, ais);
                audioformat = newformat;
            }

//checking for a supported output line
            DataLine.Info datalineinfo = new DataLine.Info(SourceDataLine.class, audioformat);
            if (!AudioSystem.isLineSupported(datalineinfo)) {
                //System.out.println("Line matching " + datalineinfo + " is not supported.");
            } else {
                //System.out.println("Line matching " + datalineinfo + " is supported.");
//opening the sound output line
                SourceDataLine sourcedataline = (SourceDataLine) AudioSystem.getLine(datalineinfo);
                sourcedataline.open(audioformat);
                sourcedataline.start();
//Copy data from the input stream to the output data line
                int framesizeinbytes = audioformat.getFrameSize();
                int bufferlengthinframes = sourcedataline.getBufferSize() / 8;
                int bufferlengthinbytes = bufferlengthinframes * framesizeinbytes;
                byte[] sounddata = new byte[bufferlengthinbytes];
                int numberofbytesread = 0;
                while ((numberofbytesread = ais.read(sounddata)) != -1) {
                    int numberofbytesremaining = numberofbytesread;
                    sourcedataline.write(sounddata, 0, numberofbytesread);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The problem with this is that my entire program stops until the sound file is finished, or at least nearly finished.

The second method is this:

    File file = new File("Launch1.wav");
    AudioClip clip;
    try {
        clip = JApplet.newAudioClip(file.toURL());
        clip.play();
    } catch (Exception e) {
        e.getMessage();
    }

The problem I have here is that every time the sound file ends early or doesn't play at all depending on where I place the code.

Is their any way to play sound without the above mentioned problems? Am I doing something wrong? Any help is greatly appreciated.

For the first method you have to create another thread for audio.

For example like this:

new Thread(
            new Runnable() {
                public void run() {
                    try {
                        // PLAY AUDIO CODE
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

Of course you have to make sure that previous sound isn't still playing.

How to play an Audio file using Java, Java sound record utility class · Java audio player sample application in Swing. Other Java Tutorials: 10 Common Mistakes Every Beginner Java  This tip will show you how -- starting with a description of the basic steps involved in playing audio clips in Java applets and then moving on to Java application support. Playing audio clips in applets is quite simple and involves the following steps: Create an AudioClip object; Load .au sound file into AudioClip; Play sounds once or loop continuously

I guess you should run your playSound method in a background thread as mentioned in the doc here

"you'll probably want to invoke this playback loop in a separate thread from the rest of the application program, so that your program doesn't appear to freeze when playing a long sound"

Maybe by doing something like

// shared executor
ExecutorService soundExecutor = ...; //Executors.newSingleThreadExecutor();
...
final File soundFile = ...;
soundExecutor.submit(new Runnable(){
   public void run(){
        SoundUtils.playSoundFile(soundFile);
   }
});

How to play back audio in Java with examples, Java FX has Media and MediaPlayer classes which will play mp3 files. Using standard javax.sound API, a single Maven dependency, completely Open need JMF (Java Media Framework); easy to integrate in any application; easy to  I'm making a java application and I need to play audio. I'm playing mainly small sound files of my cannon firing (its a cannon shooting game) and the projectiles exploding, though I plan on having looping background music. I have found two different methods to accomplish this, but both don't work how I want. The first method is literally a method:

The problem with this is that my entire program stops until the sound file is finished, or at least nearly finished.

This screams a threading issue. Have you tried playing the sound in a background thread? By the way, is this a Swing program? If so, use a SwingWorker to play the sound. There are many reasons for this, but one primary reason is that it's easy to track the state of the thread via the PropertyChangeListener support built in to SwingWorker.

Playing .mp3 and .wav in Java?, My Java sound/audio example: I'm working on a simple "meditation" application that plays a sound after a certain period of time (the sound of a  Following steps are to be followed to play a clip object. Create an object of AudioInputStream by using AudioSystem.getAudioInputStream (File file). AudioInputStream converts an audio file into stream. Get a clip reference object from AudioSystem. Stream an audio input stream from which audio data will be read into the clip by using open () method of Clip interface.

You should create a thread that handles the audio playback. But make sure that it is able to mix in sounds, so two shots that happen after each other can get their sounds played at the correct time, without waiting for the prior sound to finish. There should be Frameworks out there that do the mixing for you.

A good starting point is: http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html

Java sound example: How to play a sound file in Java , The Java Sound API is designed to help application programs play sounds smoothly and continuously, even very long sounds. Earlier you saw how to obtain a  The complete Java sound file application. If you'd like the complete source code for this Java "play sound file" application, along with the Ant build script that is used to build the application on a Mac OS X system, it's available here as my free, complete Java Mac (Swing) application.

Playing Back Audio (The Java™ Tutorials > Sound), To play sound using Clip, the process need to be alive. // Hence, we use a Swing application. public class SoundClipTest extends JFrame  Steps to play: Following are the steps to implement code for playing back an audio file (typically in .wav format) using the Clip: Create an AudioInputStream from a given sound file: 1. 2. 3. File audioFile = new File (audioFilePath); AudioInputStream audioStream = AudioSystem.getAudioInputStream (audioFile);

How to play music in Java (Simple), Playing sounds in Java is hereby easy. This works with .wav files and probably with other sound formats, such as .au files. Two versions are shown below. Once the SourceDataLine is open, you can start playing sound. You do this by invoking DataLine's start method, and then writing data repeatedly to the line's playback buffer. The start method permits the line to begin playing sound as soon as there's any data in its buffer. You place data in the buffer by the following method:

How to Play, Loop, Pause and Stop Music in Java, To play sampled audio, you create an instance of a SourceDataLine or a Clip, which acts as a source to the software audio mixer. Audio samples are then loaded into it, and delivered to the mixer. The mixer may mix the samples with those from other sources and then deliver the mix to a target (usually an audio output device on a sound card). javax.sound.Clip. Code Example: import java.io.*; import java.net.URL; import javax.sound.sampled.*; import javax.swing.*;

Comments
  • can we create a short method for this thread ? It looks quite large if we use it around :)
  • Sure, just wrap it around in some method. It isn't a blocking function.