Search code examples
javaaudioinputstream

Creating audio player in java


I'm trying to play a simply mp3 file using java. The code I have written is:

public void playAudio(String fileSource) {

  try (InputStream music = new FileInputStream(fileSource)) {
    AudioStream audioStream = new AudioStream(music);

    AudioPlayer.player.start(audioStream);
  } catch (Exception e) {
    JOptionPane.showMessageDialog(null, "error");
  }
}

but when I provide the method with the file path nothing is being played. What is the code missing? Thanks.


Solution

  • Your example can play midi, wav files, maybe some others, but not mp3, because of patent issues, but If you can use JavaFX, then you can play mp3 like this:

    import java.io.File;
    
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaPlayer;
    
    public class MainClass {
    
        public static void main(String[] args) {
            
            com.sun.javafx.application.PlatformImpl.startup(()->{});
            
            Media sound = new Media(new File("C:\\Users\\SomeUser\\Desktop\\someFile.mp3").toURI().toString());
            MediaPlayer player = new MediaPlayer(sound);
            player.play();
            
            try {
                Thread.sleep(20000); //don't exit too early
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            com.sun.javafx.application.PlatformImpl.exit();
        }
    }
    

    Otherwise you can use some other libraries like Java Stream Player

    By the way, correct syntax for your initial example is:

    InputStream in = null;
    try {
        in = new FileInputStream("someFile.wav");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    AudioStream as = null;
    try {
        as = new AudioStream(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
    AudioPlayer.player.start(as);