【发布时间】:2012-05-31 10:54:23
【问题描述】:
我正在使用 javazoom 中的库在 java 中制作 mp3Player。我已经设法启动和停止 mp3,但我无法恢复它。有人知道怎么做吗?
这是 MP3Player 类:
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();
}
}
PlayerThread 类:
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();
}
}
【问题讨论】:
-
很可能,您的
PlayerThread实现,无论它是什么,都不知道interrupt 应该会导致它暂停。 -
问题与GUI无关,与PlayerThread有关。然而,您只向我们展示了 GUI。请阅读 Thread 的 javadoc 以了解这些方法的作用,并注意您不应该使用 resume()。 docs.oracle.com/javase/6/docs/api/java/lang/Thread.html。此外,interrupt() 并不意味着暂停线程。
-
现在编辑问题。
-
我为线程 here 提供了暂停/恢复场景的示例代码。它使用
ReadWriteLock。
标签: java multithreading mp3