我剛開始使用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