ghassen92
ghassen92

Reputation: 305

play music in background java

I created "SimplePlayer" that plays music but it stops my app. I want a solution for the audio and my application ( Jframe type ) work in the same time here is my class:

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

public class SimplePlayer {
    public SimplePlayer() {
        try {
            FileInputStream fis = new FileInputStream("C:/Users/Admin/Music/B.B. King - Blues Boys Tune - YouTube.mp3");
            Player playMP3 = new Player(fis);
            playMP3.play();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

Upvotes: 0

Views: 2382

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31263

Place the Player code in a new Thread then start it :

new Thread() {

  @Override
  public void run() {
    //As your stream implements Closeable, it is better to use a "try-with-resources"
    try(FileInputStream fis = new FileInputStream("C:/Users/Admin/Music/B.B. King - Blues Boys Tune - YouTube.mp3")){
      new Player(fis).play();
    }catch(Exception e){System.out.println(e);}
  }
}.start();

Upvotes: 1

Related Questions