123

How can I play an .mp3 and a .wav file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:

public void playSound() {
    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
    } catch(Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }
}

But, this will only play .wav files.

The same with:

http://www.javaworld.com/javaworld/javatips/jw-javatip24.html

I want to be able to play both .mp3 files and .wav files with the same method.

SpaceCore186
  • 586
  • 1
  • 8
  • 22
Stan
  • 3,659
  • 14
  • 35
  • 42
  • 5
    It's worth noting that, in a `main` method, it's necessary to add a `Thread.sleep` in order to hear the sound, or else the program will end before that happens. A useful way to do that is: `Thread.sleep(clip.getMicrosecondLength() / 1000);` – André Willik Valenti May 01 '15 at 19:40
  • 1
    Looks like you'll need a plugin of some sorts. JMF should have what you need. http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html – Otra May 18 '11 at 13:27
  • Well, i'm not sure how to use these things, i've never used them before. How can I implent it, how can I use it? – Stan May 18 '11 at 16:50
  • JFM was abandoned in 2003. It is not recommended that you use it. – joshreesjones May 14 '14 at 23:42

15 Answers15

127

Java FX has Media and MediaPlayer classes which will play mp3 files.

Example code:

String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();

You will need the following import statements:

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
Community
  • 1
  • 1
jasonwaste
  • 1,310
  • 1
  • 9
  • 2
  • 4
    It worked for me but the libraries were available only in a javafx project in netbeans and used the following code – Neil Jul 14 '12 at 09:31
  • 6
    final URL resource = getClass().getResource("a.mp3"); – Neil Jul 14 '12 at 09:32
  • 1
    I had to pass `resource.toString()` to the `Media()` constructor – Ali Sep 22 '12 at 23:31
  • 52
    this isnt working for me at all. it says that the imports do not exist. and i am running java 7... – PulsePanda Nov 26 '12 at 03:09
  • 9
    http://stackoverflow.com/questions/15149547/how-do-i-work-with-javafx-in-eclipse-juno Looks like you need to manually add the javafx library from inside the Java 7 folder if you use Eclipse. – Gyurme Jun 15 '13 at 12:40
  • 7
    Technically, `Media` and `MediaPlayer` are not _Java_ classes, but _JavaFX_ classes. To add mp3 support to Java on OS X or Windows, you might want to look into [SampledSP](http://www.tagtraum.com/sampledsp.html). And yes - I wrote those libraries. – Hendrik Jul 01 '13 at 09:16
  • 9
    Don't forget you need to initialize javaFX as well for this to work. http://stackoverflow.com/questions/14025718/javafx-toolkit-not-initialized-when-trying-to-play-an-mp3-file-through-mediap – WizardsOfWor Feb 26 '14 at 15:51
  • 1
    If you don't want to rely on JavaFX, try this answer instead: http://stackoverflow.com/a/17737483/363573 – Stephan Apr 30 '14 at 10:11
  • 2
    Media m = new Media(Paths.get("YourFileName.mp3").toUri().toString()); – Amr Lotfy May 22 '15 at 11:46
  • To import JavaFX libraries in Eclipse (Luna): I use the following work around. First, go to the Build Configurations area, Libraries tab. Remove the JRE! Then, add it back in. For some unknown reason, after the library is added manually, the system is able to locate the JavaFX libraries normally. I do not know if this bug has been fixed in Mars or not. – Phil Freihofner Nov 11 '15 at 21:02
  • @jasonwaste this works great, However, there is a slight delay before the music starts playing. Is there a way to get around this? – E Shindler Feb 19 '16 at 09:08
  • I have tried this, and I don't get any errors, but the audio doesn't play. I don't know how to fix it or what to do. Could you maybe take a look at the problem [Here](http://stackoverflow.com/questions/38606289/javafx-audio-doesnt-seem-to-be-playing)? – Ryan Jul 27 '16 at 22:27
  • 1
    Please note that JavaFX comes bundled with Java 8+. If you want to use JavaFX's `MediaPlayer`, then your application also needs to extend `javafx.application.Application`, like `public class MyClass extends Application`. – Benny Code Feb 04 '17 at 00:23
  • I have error: The constructor Media(String) is undefined. Why? I downloaded javafx/javafx-ui-desktop.jar – Koss May 21 '17 at 05:07
  • Initially works on first button clicked (I have created a phone dialer app) but on second click on another button does not work. Clicking the second button a second time makes it sound again. Same goes with other buttons.. Sometimes works sometimes need a second click??? Any ideas? – Marka A Oct 10 '17 at 01:49
  • I have a requirement to play a media file to a specific audio device. java.audio supports this, but I haven't seen a way to do this using MediaPlayer. – Robbie Matthews Jul 02 '18 at 02:54
  • `MadiaPlayer` may produce memory leak – Tsyklop Oct 02 '18 at 13:47
  • I get `jfxmedia.MediaException: Could not create player!` error. –  Oct 23 '20 at 17:42
  • @Tsyklop Just googled `JavaFX MediaPlayer memory leak` and I got [this SO answer](https://stackoverflow.com/a/57015167/14270627). It says that before JavaFX 8, `MediaPlayer` had a memory leak, but most people probably no longer use JavaFX 2.2. – Tech Expert Wizard Dec 06 '20 at 19:47
  • Now that JavaFX is no longer bundled with the JDK, I think taking in JavaFX just to play MP3 audio isn't a great idea. It isn't a waste if you're also making a GUI with JavaFX, though. – Tech Expert Wizard Dec 06 '20 at 19:49
  • Doesn't work for me either! (Error: **"java.lang.ClassNotFoundException: javafx.scene.media.Media"**) Classic case for downvoting! (But I don't use to do that. I prefer indicating bad or not working code!) – Apostolos Feb 28 '22 at 12:16
35

I wrote a pure java mp3 player: mp3transform.

Thomas Mueller
  • 48,905
  • 14
  • 116
  • 132
25

Using standard javax.sound API, lightweight Maven dependencies, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:

pom.xml:

 <!-- 
    We have to explicitly instruct Maven to use tritonus-share 0.3.7-2 
    and NOT 0.3.7-1, otherwise vorbisspi won't work.
   -->
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>tritonus-share</artifactId>
  <version>0.3.7-2</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>mp3spi</artifactId>
  <version>1.9.5-1</version>
</dependency>
<dependency>
  <groupId>com.googlecode.soundlibs</groupId>
  <artifactId>vorbisspi</artifactId>
  <version>1.0.3-1</version>
</dependency>

Code:

import java.io.File;
import java.io.IOException;

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

import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;

public class AudioFilePlayer {
 
    public static void main(String[] args) {
        final AudioFilePlayer player = new AudioFilePlayer ();
        player.play("something.mp3");
        player.play("something.ogg");
    }
 
    public void play(String filePath) {
        final File file = new File(filePath);
 
        try (final AudioInputStream in = getAudioInputStream(file)) {
             
            final AudioFormat outFormat = getOutFormat(in.getFormat());
            final Info info = new Info(SourceDataLine.class, outFormat);
 
            try (final SourceDataLine line =
                     (SourceDataLine) AudioSystem.getLine(info)) {
 
                if (line != null) {
                    line.open(outFormat);
                    line.start();
                    stream(getAudioInputStream(outFormat, in), line);
                    line.drain();
                    line.stop();
                }
            }
 
        } catch (UnsupportedAudioFileException 
               | LineUnavailableException 
               | IOException e) {
            throw new IllegalStateException(e);
        }
    }
 
    private AudioFormat getOutFormat(AudioFormat inFormat) {
        final int ch = inFormat.getChannels();

        final float rate = inFormat.getSampleRate();
        return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
    }
 
    private void stream(AudioInputStream in, SourceDataLine line) 
        throws IOException {
        final byte[] buffer = new byte[4096];
        for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
            line.write(buffer, 0, n);
        }
    }
}

References:

oldo
  • 2,092
  • 1
  • 15
  • 11
  • 1
    I'm getting this error for both mp3 and ogg: UnsupportedAudioFileException: could not get audio input stream from input file – David Winiecki Jun 04 '15 at 17:04
  • I put the code into a Maven module. It definitely works: http://search.maven.org/#artifactdetails|org.guppy4j|sound-impl|0.0.3|jar – oldo Sep 03 '15 at 12:10
  • 1
    i could upgrade the version numbers to: com.googlecode.soundlibs tritonus-share 0.3.7.4 com.googlecode.soundlibs mp3spi 1.9.5.4 com.googlecode.soundlibs vorbisspi 1.0.3-2 – tibi Aug 14 '16 at 20:21
  • only verbisspi 1.0.3.3 which is the latest did not work. – tibi Aug 14 '16 at 20:22
  • This is great, it works for MP3 and WAV right out of the box! – Miles Henrichs Mar 22 '20 at 17:44
  • Using Jdk12 (OS: Windows 10), non-maven project, worked fine for WAV file. But, failed for MP3 with unsupported format exception. – RafiAlhamd Oct 20 '20 at 15:53
  • 1
    @RafiAlhamd : Make sure you have all the Maven dependencies as jars in your classpath. – oldo Oct 22 '20 at 03:51
  • For now settled with WAV. Had to do make use of only Standard JDK Libraries. Third party libraries were not permitted. Will remember to attempt for MP3, when there is a need. – RafiAlhamd Oct 27 '20 at 11:45
  • I think you don't need `vorbisspi` if you aren't also playing OGG. – Tech Expert Wizard Dec 06 '20 at 19:51
  • I have used and tried many libs so far. A lot got outdated or abandoned and broke over time, with newer formats etc.... this is an awesome example, worked right off the shelf, the libs are very small compared to other fameworks. Thanx a lot, awesome post! – JayC667 Jun 10 '21 at 11:06
  • This code doesn't play MP3 files!! ("Unsupported format error") **You are wasting people's time!** – Apostolos Mar 01 '22 at 10:03
  • @Apostolos : As you can see from other people's comments above, it worked for some as recently as June 2021. If you want us to understand why you are getting the error and be able to help, you need to provide more details (what Java version, etc), and less accusation. Maybe put your exact code with pom.xml into a public github repo for easy testing and post a link here. – oldo Mar 02 '22 at 12:18
  • @odo, thanks for your reply. I use Java 11. My code was copy-pasted from yours. I always do that when I comment on any coding in stackoverflow. But as I see, MP3 handling has been most probably removed from Oracle/Sun since you wrote your code. This is indeed very, very strange! Oracle digs Java's own grave! – Apostolos Mar 03 '22 at 06:35
  • @Apostolos : I just pasted the Java code above into a java file under src/main, and the pom.xml snippet into a section in a pom.xml, replaced the example lines with one that contains the full path to an existing mp3 file and it worked. OpenJDK 17 on Debian GNU/Linux. I could try the same with OpenJDK 11 on Windows. – oldo Mar 06 '22 at 12:53
  • I saw that. I thought it was something needed only for Maven, but as I undestand now, Maven --which I don't have and won't install just for this case!-- is the only way to reproduce an MP3! Thanks! – Apostolos Mar 07 '22 at 08:56
  • @Apostolos : Maven is a standard and convenient way to bring all required 3rd party jars into your classpath. Maven support is built into Intellij, for example, so you don't have to install anything (other than Intellij). If you want to download the required jars yourself, you can get them from "Maven Central", the huge repository of (almost) all the jars one can think of. Search for mp3spi, and don't forget the transitive dependencies. https://search.maven.org/search?q=mp3spi – oldo Mar 08 '22 at 12:38
  • @Apostolos : Maven resolves transitive dependencies for you, and if you don't use it you have to do that yourself. I did it for you: You need mp3spi 1.9.5.4, jlayer 1.0.1.4, tritonus-share 0.3.7.4, all with groupId com.googlecode.soundlibs. You can find all 3 jars on Maven Central. Download them and put them into your classpath. – oldo Mar 08 '22 at 12:47
19

you can play .wav only with java API:

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

code:

AudioInputStream audioIn = AudioSystem.getAudioInputStream(MyClazz.class.getResource("music.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();

And play .mp3 with jLayer

LittleBobbyTables - Au Revoir
  • 32,008
  • 25
  • 109
  • 114
Gustavo Marques
  • 199
  • 2
  • 2
  • 5
    This is wrong. Java will play other container formats besides wav. Furthermore, wav is a container format which can even contain mp3. So Java can not play all wav files. – Radiodef May 15 '15 at 18:12
  • 1) You missed to add a delay (idle time) which will wait until the .wav file will be produced 2) Then you should also add the method to know (programmatically) about the duration the the .wav file, for which one should wait before the program terminates and most importantly 3) It doesn't play MP3 files! (BTW, what does using jLayer will help playing MP3s???) Useless answer!. WAV files can be p;laued in various ways ... – Apostolos Mar 01 '22 at 13:22
16

It's been a while since I used it, but JavaLayer is great for MP3 playback

Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • Yes, it's very cool. Simple and doesn't seem platform dependant. Plays fine in a background and just need to figure out how to stop a thread. – James P. Aug 11 '12 at 16:00
  • https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-15250 – YaMiN Apr 09 '23 at 23:42
14

I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)

Here is a minimalistic usage example:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Required imports:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

Ivo
  • 1,768
  • 20
  • 19
  • Thanks, this is the easiest way I've tried to add mp3 support to a current application. `mp3spi1.9.4.jar` should be replaced with `mp3spi1.9.5.jar` from the java zoom site though. – Old Badman Grey Jul 29 '14 at 00:30
  • Don't forget to sleep your main thread after `player.play()` or you may not hear any sound. – jeremyjjbrown Dec 27 '14 at 23:29
8

The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Here is the code for the class

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

and here are the imports

import javazoom.jl.player.*;
import java.io.FileInputStream;
user3522940
  • 1,013
  • 2
  • 10
  • 14
Vlad
  • 142
  • 1
  • 3
  • 6
  • 1
    Yes it does check out this video [https://www.youtube.com/watch?v=LavMuqK5Is0&list=UULuXaf-zBsw8Lzz6nqr66Jw] it goes through all the functions like stop and pause. – Vlad Oct 10 '14 at 07:27
  • 1
    I think it should already contain those functions, since they seem rather basic. Anyway, I found another solution with another library, thanks for the reply :) – N3sh Oct 10 '14 at 09:36
8

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

Features:

  • very low CPU usage (~2%)
  • incredible small library (~90KB)
  • doesn't need JMF (Java Media Framework)
  • easy to integrate in any application
  • easy to integrate in any web page (as applet).

For a complete list of its methods and attributes you can check its documentation here.

Sample code:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

For more details, I created a simple tutorial here that includes a downloadable sourcecode.

UPDATE(2022)

The download link at that page does not work anymore, but there is a sourceforge project

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127
Mr. Xymon
  • 1,053
  • 2
  • 11
  • 16
4

Using MP3 Decoder/player/converter Maven Dependency.

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PlayAudio{

public static void main(String[] args) throws FileNotFoundException {

    try {
        FileInputStream fileInputStream = new FileInputStream("mp.mp3");
        Player player = new Player((fileInputStream));
        player.play();
        System.out.println("Song is playing");
        while(true){
            System.out.println(player.getPosition());
        }
    }catch (Exception e){
        System.out.println(e);
    }

  }

}
niks
  • 101
  • 3
2

You need to install JMF first (download using this link)

File f = new File("D:/Songs/preview.mp3");
MediaLocator ml = new MediaLocator(f.toURL());
Player p = Manager.createPlayer(ml);
p.start();

don't forget to add JMF jar files

antyrat
  • 27,479
  • 9
  • 75
  • 76
1

Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.

You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.

Charlie
  • 705
  • 1
  • 5
  • 14
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
  • I really have no idea how to use custom libraries, any help with it? – Stan May 20 '11 at 19:30
  • Download the library and write an include statement in your code. There should be instructions on library use included. Usually, a function call suffices, though you may need to declare an object first. Then, create a function which checks the file extension of its input, and calls the library function you want. – Spencer Rathbun May 20 '11 at 20:16
0

I have other methods for that, the first is :

public static void playAudio(String filePath){

    try{
        InputStream mus = new FileInputStream(new File(filePath));
        AudioStream aud = new AudioStream(mus);
    }catch(Exception e){
        JOptionPane.showMessageDialig(null, "You have an Error");
    }

And the second is :

try{
    JFXPanel x = JFXPanel();
    String u = new File("021.mp3").toURI().toString();
    new MediaPlayer(new Media(u)).play();
} catch(Exception e){
    JOPtionPane.showMessageDialog(null, e);
}

And if we want to make loop to this audio we use this method.

try{
    AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
    ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
    AudioPlayer.player.start(s);
} catch(Exception ex){
    JOPtionPane.showMessageDialog(null, ex);
}

if we want to stop this loop we add this libreries in the try:

AudioPlayer.player.stop(s);

for this third method we add the folowing imports :

import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
0

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Nothing worked. but this one perfectly

google and download Jlayer library first.

import javazoom.jl.player.Player;
import java.io.FileInputStream;

public class MusicPlay {

  public static void main(String[] args)  {

    try{

      FileInputStream fs = new FileInputStream("audio_file_path.mp3");
      Player player = new Player(fs);
      player.play();

    } catch (Exception e){
      // catch exceptions.
    }

  }
}
Jin Lim
  • 1,759
  • 20
  • 24
-3

Use this library: import sun.audio.*;

public void Sound(String Path){
    try{
        InputStream in = new FileInputStream(new File(Path));
        AudioStream audios = new AudioStream(in);
        AudioPlayer.player.start(audios);
    }
    catch(Exception e){}
}
  • 3
    This hasn't been the correct way to play sound for a very long time. See also [*It is a bad practice to use Sun's proprietary Java classes?*](https://stackoverflow.com/q/1834826/2891664) Your code with an empty catch block is also a terrible example. – Radiodef Jul 15 '18 at 17:43