我试图在不同的线程中同时运行 4 个 MP3 曲目。我正在使用JLayer1.0 MP3 库来播放 MP3。鉴于我无法控制线程何时启动,我使用 CountDownLatch 至少让它们同时运行。但是,每次我运行程序时,曲目都会播放,但会始终在不同的时间开始,导致它们不定时。
这是我的程序:
public class MP3 {
private String filename;
private Player player;
private final CountDownLatch runlatch;
// constructor that takes the name of an MP3 file
public MP3(String filename, CountDownLatch runlatch) {
this.filename = filename;
this.runlatch = runlatch;
}
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
System.out.println(filename);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
// run in new thread to play in background
Thread track = new Thread() {
public void run() {
try {
try {
runlatch.countDown();
runlatch.await();
player.play();
} catch (InterruptedException e) {
System.out.println(e);
}
}
catch (Exception e) { System.out.println(e); }
}
};
track.start();
}
// test client
public static void main(String[] args) throws InterruptedException {
CountDownLatch runlatch = new CountDownLatch(4);
String filename1 = args[0];
String filename2 = args[1];
String filename3 = args[2];
String filename4 = args[3];
MP3 track1 = new MP3(filename1, runlatch);
MP3 track2 = new MP3(filename2, runlatch);
MP3 track3 = new MP3(filename3, runlatch);
MP3 track4 = new MP3(filename4, runlatch);
track1.play();
track2.play();
track3.play();
track4.play();
}
}
我知道在最后一个线程打开闩锁后,我无法控制每个线程如何执行代码。看来我必须进入 JLayer1.0 实现才能更好地控制 MP3 何时开始播放。
有没有什么简单的方法可以让 MP3 曲目在整个播放过程中保持同步?我知道已经在 java 中实现了一个多轨播放器,但它似乎比我想要的更复杂。