I just want it to be able to stop halfway through playing the song but not sure how I need to do this? Does it need to be threaded?
public class playMusic {
public static void main(String[] args){
try{
FileInputStream fileInputStream = new FileInputStream("*filePath*");
Player player = new Player(fileInputStream);
player.play();
player.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(JavaLayerException e){
e.printStackTrace();
}
}
}
If you want the program to run two separate threads concurrently have a look at Concurrency/Threads. Example:
class PlayerThread extends Thread {
private final Player player;
PlayerThread(Player player) {
this.player = player;
}
public void run() {
try {
player.play();
} catch (JavaLayerException e) {
e.printStackTrace();
}
}
}
class Main {
public static void main(String[] args) throws InterruptedException {
String filename = "*filename*";
try (FileInputStream fileInputStream = new FileInputStream(filename)) {
// load the file
Player player = new Player(fileInputStream);
// start playing music in separate thread
new PlayerThread(player).start();
// wait until you want to stop the music,
// or do something else, maybe wait for user's decision
Thread.sleep(10_000); // 10 seconds
// close the player
player.close();
} catch (JavaLayerException | IOException e) {
e.printStackTrace();
}
}
this way one thread runs plays the music while you can interact with the other and give commands. Bear in mind, concurrency is a large and complex topic, if you never used it you may run into some troubles. Study the tutorial:
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html