How can I play sound in Java?

JavaAudio

Java Problem Overview


I want to be able to play sound files in my program. Where should I look?

Java Solutions


Solution 1 - Java

I wrote the following code that works fine. But I think it only works with .wav format.

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}

Solution 2 - Java

A bad example:

import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);         

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);            

// Similarly, to stop the audio.
AudioPlayer.player.stop(as); 

Solution 3 - Java

I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

private static void playSound(String sound){
    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
	URL file = cl.getResource(sound);
	final Media media = new Media(file.toString());
	final MediaPlayer mediaPlayer = new MediaPlayer(media);
	mediaPlayer.play();
}

Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

static{
	JFXPanel fxPanel = new JFXPanel();
}

Solution 4 - Java

For playing sound in java, you can refer to the following code.

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
   
// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {
   
   public SoundClipTest() {
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setTitle("Test Sound Clip");
      this.setSize(300, 200);
      this.setVisible(true);
   
      try {
         // Open an audio input stream.
         URL url = this.getClass().getClassLoader().getResource("gameover.wav");
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
         // Get a sound clip resource.
         Clip clip = AudioSystem.getClip();
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
         clip.start();
      } catch (UnsupportedAudioFileException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (LineUnavailableException e) {
         e.printStackTrace();
      }
   }
   
   public static void main(String[] args) {
      new SoundClipTest();
   }
}

Solution 5 - Java

For whatever reason, the top answer by wchargin was giving me a null pointer error when I was calling this.getClass().getResourceAsStream().

What worked for me was the following:

void playSound(String soundFile) {
    File f = new File("./" + soundFile);
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL());  
    Clip clip = AudioSystem.getClip();
    clip.open(audioIn);
    clip.start();
}

And I would play the sound with:

 playSound("sounds/effects/sheep1.wav");

sounds/effects/sheep1.wav was located in the base directory of my project in Eclipse (so not inside the src folder).

Solution 6 - Java

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Here is the code for reference.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

	AudioInputStream in;

	AudioFormat decodedFormat;

	AudioInputStream din;

	AudioFormat baseFormat;

	SourceDataLine line;

	private boolean loop;

	private BufferedInputStream stream;

	// private ByteArrayInputStream stream;

	/**
	 * recreate the stream
	 * 
	 */
	public void reset() {
		try {
			stream.reset();
			in = AudioSystem.getAudioInputStream(stream);
			din = AudioSystem.getAudioInputStream(decodedFormat, in);
			line = getLine(decodedFormat);

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

	public void close() {
		try {
			line.close();
			din.close();
			in.close();
		} catch (IOException e) {
		}
	}

	Sound(String filename, boolean loop) {
		this(filename);
		this.loop = loop;
	}

	Sound(String filename) {
		this.loop = false;
		try {
			InputStream raw = Object.class.getResourceAsStream(filename);
			stream = new BufferedInputStream(raw);

			// ByteArrayOutputStream out = new ByteArrayOutputStream();
			// byte[] buffer = new byte[1024];
			// int read = raw.read(buffer);
			// while( read > 0 ) {
			// out.write(buffer, 0, read);
			// read = raw.read(buffer);
			// }
			// stream = new ByteArrayInputStream(out.toByteArray());

			in = AudioSystem.getAudioInputStream(stream);
			din = null;

			if (in != null) {
				baseFormat = in.getFormat();

				decodedFormat = new AudioFormat(
						AudioFormat.Encoding.PCM_SIGNED, baseFormat
								.getSampleRate(), 16, baseFormat.getChannels(),
						baseFormat.getChannels() * 2, baseFormat
								.getSampleRate(), false);

				din = AudioSystem.getAudioInputStream(decodedFormat, in);
				line = getLine(decodedFormat);
			}
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}

	private SourceDataLine getLine(AudioFormat audioFormat)
			throws LineUnavailableException {
		SourceDataLine res = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class,
				audioFormat);
		res = (SourceDataLine) AudioSystem.getLine(info);
		res.open(audioFormat);
		return res;
	}

	public void play() {

		try {
			boolean firstTime = true;
			while (firstTime || loop) {

				firstTime = false;
				byte[] data = new byte[4096];

				if (line != null) {

					line.start();
					int nBytesRead = 0;

					while (nBytesRead != -1) {
						nBytesRead = din.read(data, 0, data.length);
						if (nBytesRead != -1)
							line.write(data, 0, nBytesRead);
					}

					line.drain();
					line.stop();
					line.close();

					reset();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Solution 7 - Java

There is an alternative to importing the sound files which works in both applets and applications: convert the audio files into .java files and simply use them in your code.

I have developed a tool which makes this process a lot easier. It simplifies the Java Sound API quite a bit.

http://stephengware.com/projects/soundtoclass/

Solution 8 - Java

I'm surprised nobody suggested using Applet. Use Applet. You'll have to supply the beep audio file as a wav file, but it works. I tried this on Ubuntu:

package javaapplication2;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class JavaApplication2 {

    public static void main(String[] args) throws MalformedURLException {
        File file = new File("/path/to/your/sounds/beep3.wav");
        URL url = null;
        if (file.canRead()) {url = file.toURI().toURL();}
        System.out.println(url);
        AudioClip clip = Applet.newAudioClip(url);
        clip.play();
        System.out.println("should've played by now");
    }
}
//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav

Solution 9 - Java

It works for me. Simple variant

public void makeSound(){
    File lol = new File("somesound.wav");
    

    try{
        Clip clip = AudioSystem.getClip();
        clip.open(AudioSystem.getAudioInputStream(lol));
        clip.start();
    } catch (Exception e){
        e.printStackTrace();
    }
}

Solution 10 - Java

This thread is rather old but I have determined an option that could prove useful.

Instead of using the Java AudioStream library you could use an external program like Windows Media Player or VLC and run it with a console command through Java.

String command = "\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\" \"C:/song.mp3\"";
try {
    Process p = Runtime.getRuntime().exec(command);
catch (IOException e) {
    e.printStackTrace();
}

This will also create a separate process that can be controlled it the program.

p.destroy();

Of course this will take longer to execute than using an internal library but there may be programs that can start up faster and possibly without a GUI given certain console commands.

If time is not of the essence then this is useful.

Solution 11 - Java

I faced many issues to play mp3 file format so converted it to .wav using some online converter

and then used below code (it was easier instead of mp3 supporting)

try
{
	Clip clip = AudioSystem.getClip();
	clip.open(AudioSystem.getAudioInputStream(GuiUtils.class.getResource("/sounds/success.wav")));
	clip.start();
}
catch (Exception e)
{
	LogUtils.logError(e);
}

Solution 12 - Java

import java.net.URL;
import java.net.MalformedURLException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.io.File;
public class SoundClipTest{
	//plays the sound
	public static void playSound(final String path){
		try{
			final File audioFile=new File(path);
			AudioInputStream audioIn=AudioSystem.getAudioInputStream(audioFile);
			Clip clip=AudioSystem.getClip();
			clip.open(audioIn);
			clip.start();
			long duration=getDurationInSec(audioIn);
			//System.out.println(duration);
			//We need to delay it otherwise function will return
			//duration is in seconds we are converting it to milliseconds
			Thread.sleep(duration*1000);
		}catch(LineUnavailableException | UnsupportedAudioFileException | MalformedURLException | InterruptedException exception){
			exception.printStackTrace();
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	//Gives duration in seconds for audio files
	public static long getDurationInSec(final AudioInputStream audioIn){
		final AudioFormat format=audioIn.getFormat();
		double frameRate=format.getFrameRate();
		return (long)(audioIn.getFrameLength()/frameRate);
	}
	////////main//////
	public static void main(String $[]){
		//SoundClipTest test=new SoundClipTest();
		SoundClipTest.playSound("/home/dev/Downloads/mixkit-sad-game-over-trombone-471.wav");
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpekView Question on Stackoverflow
Solution 1 - JavapekView Answer on Stackoverflow
Solution 2 - JavaGreg HurlmanView Answer on Stackoverflow
Solution 3 - JavaCyril Duchon-DorisView Answer on Stackoverflow
Solution 4 - JavaIshworView Answer on Stackoverflow
Solution 5 - JavaAndrew JenkinsView Answer on Stackoverflow
Solution 6 - Javahamilton.limaView Answer on Stackoverflow
Solution 7 - JavaStephen WareView Answer on Stackoverflow
Solution 8 - JavaNavView Answer on Stackoverflow
Solution 9 - JavaArsenView Answer on Stackoverflow
Solution 10 - JavaGalen NareView Answer on Stackoverflow
Solution 11 - JavaAdir DView Answer on Stackoverflow
Solution 12 - JavaUdesh RanjanView Answer on Stackoverflow