How to Play Background Music In Java Programs

How to Play Background Music In Java Programs: I created very simple copy-paste code for people who want to play music while running Java apps or programs. Just add your own path.

6/21/2021 2 min read

if you are looking for how to play background music or audio in Java Apps, you are in right place. It is very simple.

import javax.sound.sampled.AudioInputStream;
import
javax.sound.sampled.AudioSystem;
import
javax.sound.sampled.Clip;
import
javax.swing.*;
import
java.io.*;

class
Player {
        void playMusic(String musicLoc){
                 try {
                         File musicPath = new File(musicLoc);
                          if
(musicPath.exists()){ 
                                  AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
                                  
Clip clip = AudioSystem.getClip();
                                  
clip.open(audioInput);
                                 
clip.start();
                                 
JOptionPane.showMessageDialog(null,"Press ok to stop playing");

                           }
                          else{
                                   System.out.println("Couldn't find Music file");
                                
}
                }
                catch (Exception ex){
                           ex.printStackTrace();
                     
}
           }
}

Now, we are very close. Let see the Main method. Keep in mind this method is only working for .waw file. But don't worry if you have any other files just convert them using this website: https://cloudconvert.com/mp3-to-wav.

public class Main {

public static void main(String[] args) {

           //Add your own path
            String filePath =
                     "/Users/muradnabizade/Downloads/Corporate Business Music by Infraction [No Copyright Music 2019] Business (1).wav";
                      
Player play = new Player();
                     
play.playMusic(filePath);
            
}
}

After this, you can enjoy your music while running your Java program.