我刚开始使用Jlayer库播放MP3。它完美的工作,我可以播放歌曲。我唯一的问题是实现暂停和恢复方法。由于我对多线程的知识有限,所以我通过制作线程来播放MP3等待,声音将停止,为了恢复歌曲,我只需要通知该线程。以下是我的了:JLayer暂停和恢复
import java.util.Scanner;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 extends Thread{
private String filename;
private Player player;
private Thread t;
private volatile boolean continuePlaying = true;
// constructor that takes the name of an MP3 file
public MP3(String filename) {
this.filename = filename;
}
public void close() { if (player != null) player.close(); }
// play the MP3 file to the sound card
public void play() {
try {
FileInputStream fis = new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
}
catch (Exception e) {
System.out.println("Problem playing file " + filename);
System.out.println(e);
}
}
public void run() {
play();
try {
while (true) {
synchronized(this) {
while(!continuePlaying)
wait();
player.play();
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
private void pause() throws InterruptedException{
System.out.println("Pause");
continuePlaying = false;
}
private void resumeSong() throws InterruptedException{
synchronized(this) {
System.out.println("Resume");
continuePlaying = true;
notify();
}
}
// test client
public static void main(String[] args) throws InterruptedException{
String filename = ("Fall To Pieces.mp3");
MP3 mp3 = new MP3(filename);
mp3.start();
Scanner s = new Scanner(System.in);
s.nextLine();
mp3.pause();
s.nextLine();
mp3.resumeSong();
try {
mp3.join();
} catch (Exception e){
}
}
}
出于某种原因,然而,等待()什么都不做,程序甚至没有达到通知()。这是为什么发生?
我读过以前的关于这个问题的SO问题,但我一直无法让它们工作。我也有兴趣了解为什么这段代码不工作,所以我可以进一步理解多线程。谢谢!
解决方案是在这里:http://stackoverflow.com/questions/12057214/jlayer-pause-and-resume-song – pi4630