[Java] Add background music to JFrame

You can call this method to play loop-able background music. Don’t forget to change the path to the wav file. I’ve to warn you, only WAV files work!

        import sun.audio.AudioData;
        import sun.audio.AudioPlayer;
        import sun.audio.AudioStream;
        import sun.audio.ContinuousAudioDataStream;

        public void startBGMusic() { //Plays the background music
            //make a new AudioPlayer.
              AudioPlayer myBackgroundPlayer = AudioPlayer.player;

              ContinuousAudioDataStream myLoop = null;
  			//use a try block in case the file doesn't exist.
              try {
              AudioStream myBackgroundMusic = new AudioStream(new FileInputStream(new File(getClass().getResource(
            		  "/com/wordpress/ahesham/resources/tabla.wav").toURI())));
              AudioData myData = myBackgroundMusic.getData();
              myLoop = new ContinuousAudioDataStream(myData);
              }
              catch(Exception error) {JOptionPane.showMessageDialog(null, "Invalid file!");}

              // play background music.
              myBackgroundPlayer.start(myLoop);
        }
Advertisements

3 comments

    • For this to work you have to import 4 libraries; however, I forgot to put them in the post. I’ve updated the code with the correct imports and here they are:

      import sun.audio.AudioData;
      import sun.audio.AudioPlayer;
      import sun.audio.AudioStream;
      import sun.audio.ContinuousAudioDataStream;

  1. hello. i have an error in this part : myBackgroundMusic = new AudioStream(new FileInputStream(“canon.wav”)); it says it cannot find symbol


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s