我正在使用 Java swing 构建应用程序。该应用程序基本上从 Broadcastify 网站抓取警察广播流并播放它们。
目前的应用程序有两个按钮:“芝加哥警察”、“芝加哥消防和 EMS”。当按下 Chicago Police 按钮时,Chicago Police 流开始播放。但是,当按下相同的按钮或不同的按钮时,流不会停止,它们只是在自己播放。我认为这与 SwingWorker 有关。
基本上,我想要它做的是播放一个流,当按下另一个流按钮时,停止当前流,然后启动新流。
我曾尝试使用 .cancel(true) 方法,但这不起作用。
这是我的代码 -
框架类:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class frame extends JFrame{
private JPanel north, south;
private JButton chicagoPolice, chicagoFireEms;
private JTextField status;
stream s = new stream();
public frame(){
//set title
super("Broadcastify Streams");
//north panel
north = new JPanel();
north.setPreferredSize(new Dimension(500,250));
north.setBackground(Color.RED);
add(north, BorderLayout.NORTH);
//Chicago Police button
chicagoPolice = new JButton("Chicago Police");
north.add(chicagoPolice);
//Chicago Fire and EMS
chicagoFireEms = new JButton("Chicago Fire and EMS");
north.add(chicagoFireEms);
//south panel
south = new JPanel();
south.setBackground(Color.BLUE);
add(south, BorderLayout.SOUTH);
//status bar
status = new JTextField(15);
status.setEditable(false);
south.add(status, BorderLayout.NORTH);
//button action listeners
chicagoPolice.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
s.setStream("http://relay.broadcastify.com:80/il_chicago_police2");
s.playStream();
status.setText("Playing - Chicago Police");
}
});
chicagoFireEms.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
s.setStream("http://relay.broadcastify.com:80/836454979");
s.playStream();
status.setText("Playing - Chicago Fire and EMS");
}
});
}
}
流类:
import java.net.URL;
import java.net.URLConnection;
import javax.swing.SwingWorker;
import javazoom.jl.player.Player;
public class stream {
private SwingWorker<Void,Void> worker;
private String stream;
private Player player;
public stream(){
stream = "";
}
public void setStream(String radioStream){
stream = radioStream;
}
public void playStream(){
worker = new SwingWorker<Void,Void>(){
public Void doInBackground() throws Exception{
URLConnection urlConnection = new URL(stream).openConnection();
urlConnection.connect();
player = new Player(urlConnection.getInputStream());
player.play();
return null;
}
};
worker.execute();
}
}
主类:
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
frame f = new frame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.setResizable(false);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
有人可以将它放入 Eclipse 并对其进行测试,看看我在说什么。您还需要在这里找到的 JLayer 库:http ://www.javazoom.net/javalayer/javalayer.html
谢谢。