我只想让它在播放歌曲的中途停止,但不知道该怎么做?它需要穿螺纹吗?
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();
}
}
通过这种方式,一个线程运行时播放音乐,而您可以与另一个线程交互并发出命令。请记住,并发是一个庞大而复杂的主题,如果你从未使用过它,你可能会遇到一些麻烦。学习教程:
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.htmlhttps://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html