방금 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){
}
}
}
그러나 어떤 이유로 wait()는 아무 것도하지 않고 프로그램이 notify()에 도달하지도 않는다. 왜 이런 일이 일어나는 걸까요?
나는 이것에 대한 이전의 SO 질문을 읽었지만 제대로 작동하지 못했습니다. 또한 왜이 코드가 작동하지 않는지에 관심이 많아서 멀티 스레딩을 더 잘 이해할 수 있습니다. 고맙습니다!
해결책은 여기에 있습니다. http://stackoverflow.com/questions/12057214/jlayer-pause-and-resume-song – pi4630