简体   繁体   中英

How to play an mp3 file given an absolute file name?

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?

  • 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();
} 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM