在Linux系统下制作一个简单的MP3播放器
代码(一个简单的GUI,通过菜单打开文件并播放,要停止播放直接关闭窗口即可。)
/**
* @kissplayer.java
*
*
* @author
* @version 1.00 2007/10/13
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.io.*;
import javax.media.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
class KissFrame extends JFrame{
KissFrame() {
super("Simple Video Player");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JMenuBar jmb = new JMenuBar();
JMenu jMenu1 = new JMenu("文件");
JMenu jMenu2 = new JMenu("控制");
JMenuItem jMenuItem1_1 = new JMenuItem("打开");
JMenuItem jMenuItem1_2 = new JMenuItem("退出");
jmb.add(jMenu1);
jmb.add(jMenu2);
jMenu1.add(jMenuItem1_1);
jMenu1.add(jMenuItem1_2);
// Add action HERE
MenuItemListener listener = new MenuItemListener();
jMenuItem1_1.addActionListener(listener);
setJMenuBar(jmb);
Container contentPane = getContentPane();
}
private class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// System.out.println("jMenuItem1_1");
JFileChooser chooser = new JFileChooser("."); // "."表示本目录
int result = chooser.showOpenDialog(null);
if(result == chooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
SimpleAudioPlayer.beginPlay(selectedFile);
}
else if(result == chooser.CANCEL_OPTION)
{
// 用户取消了操作
}
}
}
public static void main (String[] args) {
KissFrame sf = new KissFrame();
sf.setVisible(true);
}
}
class SimpleAudioPlayer {
private Player audioPlayer = null;
public SimpleAudioPlayer(URL url) throws IOException,
NoPlayerException,
CannotRealizeException {
audioPlayer = Manager.createRealizedPlayer(url);
}
public SimpleAudioPlayer(File file) throws IOException,
NoPlayerException,
CannotRealizeException {
this(file.toURL());
}
public void play() {
audioPlayer.start();
}
public void stop() {
audioPlayer.stop();
audioPlayer.close();
}
public static void beginPlay(File audioFile) {
try {
SimpleAudioPlayer player = new SimpleAudioPlayer(audioFile);
player.play();
// player.stop();
} catch(IOException e) {
System.out.println(e.getMessage());
} catch(NoPlayerException ee) {
System.out.println(ee.getMessage());
} catch(CannotRealizeException eee) {
System.out.println(eee.getMessage());
}
}
}
(责任编辑:云子)