无法停止歌曲,因为它必须在其他台词之前结束 运行

Can't stop song because it has to end before other lines run

我只是希望它能够在播放歌曲的中途停止,但不确定我需要怎么做?需要穿线吗?

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();
      }
   }
}

如果您希望程序 运行 两个独立的线程并发查看 Concurrency/Threads。 示例:

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();
        }
    }

这样一个线程 运行s 播放音乐,而您可以与另一个线程交互并发出命令。请记住,并发是一个庞大而复杂的主题,如果您从未使用过它,您可能 运行 会遇到一些麻烦。学习教程:

https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html