Reputation: 37
Here is my code:
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
}
}
I wanted to create an mp3-player and found this Project, what the code snippet does is creating a new MP3Player object, creating a new File, and adding it to the Playlist. After that, it just starts playing the song. But the problem is that it just plays about one or two seconds of the file before the program stops executing. How can I wait until the play() function has stopped executing?
Answer: Thanks to giraycoskun for this!
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++;
}
}
}
I had to do some minor changes to the answer he submitted, but it works great, thank you very much!
Upvotes: 0
Views: 69
Reputation: 161
I haven't tried the code on my computer however these can help:
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...");
}
}
}
Upvotes: 1