Pages

Ads 468x60px

Monday, March 11, 2013

Java: Play Background Music



You can use following code to play background music in your Java application. You will need to add 'jl1.0.jar' in your Java project. You can download it from
http://www.javazoom.net/javalayer/sources.html


BackgroundMusic.java:


import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;

public class BackgroundMusic {

    private String filename;
    private static Player player;
    Thread playMusic;
    // constructor that takes the name of an MP3 file

    public BackgroundMusic(String filename) {
        this.filename = filename;
    }

    // play the MP3 file to the sound card
    public void play() {
        try {
            FileInputStream fis = new FileInputStream(filename);
            BufferedInputStream bis = new BufferedInputStream(fis);
            player = new Player(bis);
        } catch (Exception e) {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        }
    }

    public void start() {
        play();
        playMusic = new Thread(new PlayMusic());
        playMusic.start();
    }

    public void stop() {
        close();
        playMusic = null;
    }

    public void close() {
        if (player != null) {
            player.close();
        }
    }

    class PlayMusic implements Runnable {

        public void run() {
            try {
                player.play();
            }
            catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}


TestBackgroundMusic.java:

import java.util.logging.Level;
import java.util.logging.Logger;

public class TestBackgroundMusic {
    
    public static void main(String[] args){
        
        try {
            BackgroundMusic bm = new BackgroundMusic("FileName.mp3");
            bm.start();
            Thread.sleep(10000);
            bm.stop();
        } catch (InterruptedException ex) {
            System.out.println(ex);
        }
    }
    
}

2 comments:

  1. Thanks, very nice tutorial!

    ReplyDelete
  2. What about a loop endless loop? My blog https://isjavado.wordpress.com/contents/ and https://www.facebook.com/bsjug.java.1

    ReplyDelete