2

I've found some would-be answers on Stack Overflow, but they are old and it looks like they use deprecated technologies.

I need to play an mp3 file given an absolute file name.

Here is what I've tried:

1. JavaFX

MediaPlayer player = new MediaPlayer(new Media(uriString)); 

I am getting java.lang.IllegalStateException: Toolkit not initialized.

I could probably find a way to initialize that toolkit, but I'd like to know if it's the preferred way.

2. Intellij UIUtil

final InputStream is = new FileInputStream(fileName);

UIUtil.playSoundFromStream(new Factory<InputStream>() {
    @Override
    public InputStream create() {
        return is;
    }
});

I am getting Audio format is not yet supported: could not get audio input stream from input file

I've made some more attempts, but this is what I have a record of.

The only thing that's working for me so far is playing files from shell: on Mac,

Runtime.getRuntime().exec("afplay " + filePath);

But I'd prefer a Java solution. Any ideas?

boraseoksoon
  • 2,164
  • 1
  • 20
  • 25
Irina Rapoport
  • 334
  • 3
  • 10

1 Answers1

2
  • For JavaFX

You can have a look here Getting a mp3 file to play using javafx

  • Here you are,my favourite part:

You can use JLayer which supports .mp3.

Example

new Thread(()->{
   try {
        FileInputStream file = new FileInputStream("path ..../audio.mp3"); //initialize the FileInputStream
        Player player= new Player(file); //initialize the player
        player.play(); //start the player
    } catch (Exception e) {
       e.printStackTrace();
    }

 }).start();

Note:

Note that i am using a separate Thread cause if not the application will stack.

Generally Speaking:

You have to use external libraries to play files like .mp3 in Java(although JavaFX supports .mp3 but not all formats)

Java supports only .wav

Although that's enough.All you need is an external algorithm to play other music formats.All the other format's come originally from .wav,they pass into an algorithm and then boom they become .ogg,.mp3,.whatever

1.As mentioned before for .mp3 JLayer.jar You can import this jar into your project as an external library.

2.JavaZoom has also and other libraries to support .ogg,.speex,.flac,.mp3,follow the link above and download the jlGui project there you can find libraries for a lot of formats.

Link to stackoverflow on How to play .wav files with java

And http://alvinalexander.com/java/java-audio-example-java-au-play-sound Not sure if that still works with java 8

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.Clip;
   import javax.sound.sampled.DataLine;
   import javax.sound.sampled.LineEvent;
   import javax.sound.sampled.LineListener;
   import javax.sound.sampled.LineUnavailableException;
   import javax.sound.sampled.UnsupportedAudioFileException;


 public class AudioPlayerExample1 implements LineListener {

/**
 * this flag indicates whether the playback completes or not.
 */
boolean playCompleted;

/**
 * Play a given audio file.
 * @param audioFilePath Path of the audio file.
 */
void play() {
    File audioFile = new File("C:/Users/Alex.hp/Desktop/Musc/audio.wav");

    try {
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

        AudioFormat format = audioStream.getFormat();

        DataLine.Info info = new DataLine.Info(Clip.class, format);

        Clip audioClip = (Clip) AudioSystem.getLine(info);

        audioClip.addLineListener(this);

        audioClip.open(audioStream);

        audioClip.start();

        while (!playCompleted) {
            // wait for the playback completes
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        audioClip.close();

    } catch (UnsupportedAudioFileException ex) {
        System.out.println("The specified audio file is not supported.");
        ex.printStackTrace();
    } catch (LineUnavailableException ex) {
        System.out.println("Audio line for playing back is unavailable.");
        ex.printStackTrace();
    } catch (IOException ex) {
        System.out.println("Error playing the audio file.");
        ex.printStackTrace();
    } 
}

/**
 * Listens to the START and STOP events of the audio line.
 */
@Override
public void update(LineEvent event) {
    LineEvent.Type type = event.getType();

    if (type == LineEvent.Type.START) {
        System.out.println("Playback started.");

    } else if (type == LineEvent.Type.STOP) {
        playCompleted = true;
        System.out.println("Playback completed.");
    } 
}

public static void main(String[] args) {
    AudioPlayerExample1 player = new AudioPlayerExample1();
    player.play();
} 

}

Community
  • 1
  • 1
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
  • Thank you for a great answer. Looks like all solutions except for the last one rely on 3rd party libraries. About the last one - do you think it might play mp3? – Irina Rapoport Sep 29 '16 at 01:35
  • @Irina Rapoport I edited the answer,so at the beginning it includes a link with solutions on `JavaFX`.The code at the end is only for `.wav` files.If you want to use third party libraries like `JLayer`,it is so easy as you import the .jar into the project,you run the code at the begging and voila! – GOXR3PLUS Sep 29 '16 at 01:41
  • 1
    Thank you for the edit. True RE 3rd party .jar, but I don't run obscure 3rd party code without reading it first, and who has the time for this? – Irina Rapoport Sep 29 '16 at 04:51
  • @Irina Rapport :) lmao,if you want to learn you can always find time. + The name Irina is derived from the ancient Greek goodess of peaceful life Eirene. In Ancient Greek εἰρήνη means peace, i learned it now .. – GOXR3PLUS Sep 29 '16 at 04:54
  • playing audio is always playing wave. playing mp3 is uncompress then playing audio wave – Tokazio Sep 29 '16 at 05:07
  • 1
    It's basic security. Helps me stay peaceful :-) – Irina Rapoport Sep 29 '16 at 17:30