I am making a mp3Player in java with the library from javazoom. I have manged to start and stop the mp3 but i cant resume it. Does anyone know how to do this?
Here is the MP3Player class:
public class MP3Player extends JFrame{
public MP3Player(){
JPanel jpBottom = new JPanel();
JButton btnPlay = new JButton("Play");
JButton btnPause = new JButton("Pause");
jpBottom.add(btnPause);
jpBottom.add(btnPlay);
Container cp = this.getContentPane();
BorderLayout bl = new BorderLayout();
cp.setLayout(bl);
cp.add(jpBottom, BorderLayout.SOUTH);
btnPlay.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(t.isInterrupted()){
t.resume();
} else{
t.start();
}
}
}
);
btnPause.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
t.interrupt();
}
}
);
this.setVisible(true);
this.setSize(250, 100);
this.setTitle("MP3 Player");
this.setLocation(100, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Thread t = new Thread(new PlayerThread("file:///C://a.mp3"));
public static void main(String[] args) {
MP3Player n = new MP3Player();
}
}
The PlayerThread class:
public class PlayerThread implements Runnable{
String path;
PlayerThread(String path){
this.path = path;
}
public void run(){
try{
URL url = new URL(path);
InputStream in = url.openStream();
AdvancedPlayer pl = new AdvancedPlayer(in);
pl.play();
}
catch(Exception e){
System.out.println("Error: "+e);
}
}
public void pause(){
Thread.interrupted();
}
}
It looks like you’re making a lot of assumptions that things will “just work”, without reading the APIs for the libraries you’re using.
Firstly, interrupting a thread simply sets a flag on that thread. By convention, blocking calls will usually inspect this flag periodically and terminate early by throwing an
InterruptedExceptionif that is the case. But that’s not an automatic guarantee, and a caller cannot forcibly interrupt another thread. You need to ensure that interruption will do what you expect.Your
pause()method is doubly wrong in that you’re not even setting the interrupted flag;Thread.interrupted()checks whether the current thread is interrupted (returning a boolean).Let’s go back to basics – you’re playing sound by calling
AdvancedPlayer.play(). How do you get an AdvancedPlayer to pause? Looking through its documentation, it seems like it doesn’t support pausing in any obvious way. (There’s astop()method but I don’t believe it would resume from the same place). And since the method doesn’t throwInterruptedException, it’s almost guaranteed that it doesn’t respond to interrupts.However, there is a
BasicPlayerclass that does have a pause. Is there any reason why you couldn’t use that instead, something like (ignoring exceptions):