【发布时间】:2015-06-17 15:41:33
【问题描述】:
我正在开发一个可以播放由 MP3 组成的播放列表的程序。
我正在使用以下 MP3 类
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioInputStream;
import javazoom.jl.player.Player;
public class MP3 {
private Player player;
public BufferedInputStream bis;
// constructor
public MP3() {
}
public void close() throws IOException {
if (player != null)
player.close();
}
// play the MP3 file to the sound card
public void play(String filename) {
try {
InputStream stream = MP3.class.getClassLoader()
.getResourceAsStream(filename);
bis = new BufferedInputStream(stream);
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
new Thread() {
public void run() {
try {
player.play();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
}
我已经能够播放基于此代码的 MP3 文件,但我无法播放多个文件。当我第一次尝试播放 MP3 的 ArrayList 时,所有歌曲都相互播放。然后我尝试使用 .wait 方法让第二首歌曲等到第一首歌曲播放完毕。但是,这很有效,这也使我的程序中的所有内容都等到歌曲播放完毕后才能执行其他任何操作。我希望我的程序能够在播放歌曲时执行多项操作,这样该方法就不起作用了。
这是我目前拥有的使用 .wait 的代码
} else if (e.getSource() == btn2) {
ArrayList<Integer> songsToPlay = new ArrayList<Integer>();
songsToPlay.add(1);
songsToPlay.add(2);
if (b2 == false) {
b2 = true;
mp3 = new MP3();
//loop through the ArrayList of songs
for (int i = 0; i < songsToPlay.size(); i++) {
mp3.play("music/" + songsToPlay.get(i) + ".mp3");
synchronized (mp3) {
try {
mp3.wait(1000);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
// e2.printStackTrace();
}
}
}
} else {
b2 = false;
try {
mp3.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
// e1.printStackTrace();
}
}
}
任何建议都会很棒,因为我已经坚持了一段时间。此外,如果我想找到一种使用 .wait 的方法,我还需要一种方法来计算当前 MP3 的长度。现在我只是硬编码值。
【问题讨论】:
-
我猜你不想阻止这个程序,为此,我建议实现一个Observer Pattern 来确定是否有歌曲正在播放......
标签: java synchronization mp3 wait