【问题标题】:How do I wait for a command to finish executing before stopping the program?如何在停止程序之前等待命令完成执行?
【发布时间】:2021-05-16 09:51:59
【问题描述】:

这是我的代码:

import java.io.File;
import jaco.mp3.player.MP3Player;

class SimpleAudioPlayer {

    public static void main(String[] args) {

        File audio_file = new File("Clarx - H.A.Y.mp3");
        MP3Player music_player = new MP3Player();
        music_player.addToPlayList(audio_file);
        music_player.play();
        // wait for music_player.play() to finish executing
    }
}

我想创建一个 mp3 播放器,发现 this Project,代码 sn-p 所做的是创建一个新的 MP3Player 对象,创建一个新文件,并将其添加到播放列表中。之后,它才开始播放歌曲。但问题是在程序停止执行之前它只播放了大约一两秒的文件。如何等到 play() 函数停止执行?

答案: 感谢 giraycoskun !

import java.io.File;
import jaco.mp3.player.MP3Player;
import java.util.concurrent.*;

class SimpleAudioPlayer {

    public static void main(String[] args) {

        File audio_file = new File("Clarx - H.A.Y.mp3");
        MP3Player music_player = new MP3Player();
        music_player.addToPlayList(audio_file);
        ExecutorService threadpool = Executors.newCachedThreadPool();
        Future<Long> futureTask;
        futureTask = (Future<Long>) threadpool.submit(music_player::play);
        // Simple variable to check hpw often the folowing loop gets executed
        int n = 0;
        while (!futureTask.isDone()) {
            System.out.println("Executing" + n);
            n++;
        }
    }
}

我不得不对他提交的答案做一些小改动,但效果很好,非常感谢!

【问题讨论】:

    标签: java mp3 wait


    【解决方案1】:

    我还没有在我的计算机上尝试过代码,但是这些可以提供帮助:

    https://docs.oracle.com/javase/8/docs/api/?java/util/concurrent/package-summary.html

    https://www.baeldung.com/java-asynchronous-programming

    import java.io.File;
    import jaco.mp3.player.MP3Player;
    import java.util.concurrent;
    
    class SimpleAudioPlayer {
    
        public static void main(String[] args) {
    
            File audio_file = new File("Clarx - H.A.Y.mp3");
            MP3Player music_player = new MP3Player();
            music_player.addToPlayList(audio_file);
            ExecutorService threadpool = Executors.newCachedThreadPool();
            Future<Long> futureTask = threadpool.submit(() -> music_player.play());
            while (!futureTask.isDone()) {
                // wait for music_player.play() to finish executing
                System.out.println("FutureTask is not finished yet..."); 
            } 
            
            
        }
    }
    

    【讨论】:

    • 非常感谢。我不得不对代码做一些小的改动,但它可以按我的意愿工作。
    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2020-05-27
    • 2018-08-31
    相关资源
    最近更新 更多