One function in my program is to playback an Mp3 file. I'm using the JLayer Library (http://www.javazoom.net/javalayer/javalayer.html) to accomplish this.
Also, to prevent blocking of the program while the song plays, I want to use Threads. See this code snippet:
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class P2PClient {
private static Player player;
public static void main (String[] args) {
try {
play(args[0]);
} catch (FileNotFoundException | javazoom.jl.decoder.JavaLayerException e) {
e.printStackTrace();
}
System.out.println("Hello");
player.close();
}
private static void play(String track) throws FileNotFoundException, javazoom.jl.decoder.JavaLayerException {
new Thread() {
private Player player = new Player(new FileInputStream(track));
@Override
public void run() {
try {
P2PClient.player = this.player;
player.play();
} catch (javazoom.jl.decoder.JavaLayerException e) {
e.printStackTrace();
}
}
}.start();
}
}
The playback works. Also, the "Hello" is printed, therefore I know that play(args[0])
is not blocking the current thread. What's not working is the player.close()
line... Instead I get a NullPointerException in this line.
I want to have a reference to player
in the anonymous thread instance and still "autostart" the thread with the call to void play(String track)
. Therefore I resort to a little ugly method of declaring a private static Player
variable in the P2PClient
class.
I don't understand why I'm getting this NullPointerException... If this is an incorrect way of accomplishing what I want, how do I get a player
reference without returning a Thread
object?