我只是希望它能够在播放歌曲时中途停止,但不确定我该怎么做?是否需要穿线?
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();
}
}
}
答案 0 :(得分:0)
如果您希望程序同时运行两个单独的线程,请查看并发/线程。 示例:
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();
}
}
这样,一个线程运行时会播放音乐,而您可以与另一个线程交互并发出命令。请记住,并发是一个大而复杂的主题,如果您从未使用过它,则可能会遇到一些麻烦。学习教程:
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html