Josh Walshaw
Josh Walshaw

Reputation: 210

Can't Loop MP3 File

Okay so I'm trying to get a sound file looped forever whilst the application is open. This is currently the piece of code I've got which runs the sound file.

public class Game {

    public static void main(String[] args) {

        JFrame window = new JFrame("Josh's 2D College Project");
        window.setContentPane(new GamePanel());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.pack();
        window.setVisible(true);

        try{

            File file = new File("C:/Users/Josh Scott (Zinotia)/Desktop/2D College Project/Resources/Sounds/BGSong.mp3");
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);

            try{

                Player player = new Player(bis);
                player.play();

            } catch(JavaLayerException ex) {}

        } catch(IOException e){} 
    }
}

I'm using JavaZoom's JavaLayer in order to play the Mp3 file. Could anyone possibly give me another way to loop & use the sound file either with a different way or using the JavaLayer.

Upvotes: 3

Views: 978

Answers (2)

Martin Frank
Martin Frank

Reputation: 3474

Add an Listener to the player;

this can be done if you're using the AdvancedPlayer instead of the Player .

AdvancedPlayer p = new AdvancedPlayer(bis)
p.setPlayBackListener(new Playbacklistener(){

    //override unimplemented methods
    @Override
    public void playbackFinished(PlaybackEvent evt){
        p.start()
    }

    @Override
    public void playbackStarted(PlaybackEvent evt){}
};

NOTE - this are only fragments, you need to integrate it into your code...

Upvotes: 2

Mitch Zinck
Mitch Zinck

Reputation: 312

First, get how long the mp3 file exactly is. Then inside the second try statement add a while(true) and inside that add the

player.play();

and then add this

thread.Sleep(//mp3 length in milliseconds here)

It should look like this:

try {
     Player player = new Player(bis);
     while(true) {
        player.play();
        Thread.Sleep(69000); //length of mp3 here
     }
}

You could also try

try {
     Player player = new Player(bis);
     while(true) {
        player.play();
     }
}

But I am not sure if that would work or just keep playing the sound instantly over and over again.

Upvotes: 1

Related Questions