📄 mediaplayer.java
字号:
}
}
);
System.out.println("注意:更新文件列表后,请先正常关闭播放器"
+ "\n然后再关闭此DOS窗口,否则导4致播放列表不能保存!!");
}
catch(Exception e){
e.printStackTrace();
}
}
private void openFile()// 为了界面原因,此代码重写,估计兼容性不好了
{
/*
* JFileChooser fileChooser=new JFileChooser();//文件选择器
* fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//可以选择文件不能目录
* int result=fileChooser.showOpenDialog(this);//创建文件打开对话框,并设定此程序为父窗口监控
*/
/*
* 通过result的值来判断文件是否打开成功 JFileChooser类有很多静态成员变量
*/
/*
* if(result==JFileChooser.CANCEL_OPTION) {
* file=null;//file已经在类中定义,如果选择取消,file指向为空 } else {
* file=fileChooser.getSelectedFile();//获得文件对象
* title=file.getAbsolutePath();//取得文件的绝对路径并且赋给title设定标题 }
*/
// if(fd==null)
// {
// String filename="java音频播放器";
fd = new FileDialog(MediaPlayer.this);
// Filters fl=new Filters();
// fd.setFilenameFilter(fl);
fd.setVisible(true);
if (fd.getFile() != null) {
title = fd.getDirectory() + fd.getFile();// 原因请见同目录下的FileDialogDemo.java文件
files = fd.getFile();
// dir =fd.getDirectory();
file = new File(title);
createPlayer();
}
// title=filename;
// fd=null;//缺少此句如果第一次打开文件的时候取消操作的时候第二次也不能打开文件了
// }
}
@SuppressWarnings("unchecked")
private void openDir() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fileChooser.showOpenDialog(MediaPlayer.this);
if (result == JFileChooser.CANCEL_OPTION)
return;
file = fileChooser.getSelectedFile();
if (file == null || file.getName().equals(""))
JOptionPane.showMessageDialog(this, "错误的路径", "出错了",
JOptionPane.ERROR_MESSAGE);
String[] sFiles = file.list();
for (int i = 0; i < sFiles.length; i++) {
fileName.addElement(sFiles[i]);
numList.addElement((numList.size() + 1) + "." + sFiles[i]);
dirName.addElement(file.getAbsolutePath() + "\\" + sFiles[i]);
}
list.setListData(numList);
/*
* fd=new FileDialog(MediaPlayer.this); fd.setVisible(true);
* if(fd.getDirectory()!=null) { File fileDir=new
* File(fd.getDirectory()); String[] ss=fileDir.list(); for(int i=0;i<ss.length;i++) {
* System.out.println(ss[i]); } }
*/
}
public void startPlayer(){
SwingWorker worker = new SwingWorker() {
public Object construct() {
try {
Thread.sleep(5);
player.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
return "OK";
}
public void finished() {
return;
}
};
worker.start();
}
@SuppressWarnings("deprecation")
private void createPlayer() {
closePreviosPlayer();// 关闭先前的媒体播放器
String extendName = "此播放器好象不支持"
+ title.substring(title.lastIndexOf(".") + 1) + "格式";
try {
player = Manager.createPlayer(file.toURL());// javax.media.Manager直接继承于java.lang.object,且它为final,不能被继承
player.addControllerListener(new ControllerHand());
//startPlayer();
player.start();
addList(files);
index = fileName.size() - 1;
list.setSelectedValue(numList.elementAt(index), true);
// list.setSelectedIndex(index);
// list.setSelectionForeground(Color.blue);
setTitle(files);
// addList("files");//到播放清单
// title="file.getAbsoluteFile()";
} catch (Exception e) {
JOptionPane.showMessageDialog(this, extendName, "出错了!!",
JOptionPane.ERROR_MESSAGE);
setTitle(extendName);
}
}
private void closePreviosPlayer() {
if (player == null)
return;
// player.close();//首先停止播放
/*
* 不能用上面的代码停止,要用下面的两行取代,否则Component visual
* =player.getVisualComponent();发生异常
*/
player.stop();
player.deallocate(); // 停止播放并且重新装载DateSource
Component visual = player.getVisualComponent();
Component control = player.getControlPanelComponent();
if (visual != null) {
panel.remove(visual);
}
if (control != null) {
panel.remove(control);
}
}
private class ControllerHand implements ControllerListener {
public void controllerUpdate(ControllerEvent e) {
if (e instanceof RealizeCompleteEvent) {
Component visual = player.getVisualComponent();
if (visual != null) {
// System.out.println("音频播放器不支持视频图象功能");
// setTitle("音频播放器不支持视频图象功能");
panel.removeAll();
panel.add(visual, BorderLayout.CENTER);
} else {
panel.add(label, BorderLayout.CENTER);
}// /此else语句可以防止因为原来播放视频图象后以后没有界面
Component control = player.getControlPanelComponent();
if (control != null) {
panel.add(control, BorderLayout.SOUTH);
}
// c.validate();
panel.doLayout();
return;
}
if (e instanceof EndOfMediaEvent) {
/*
* if (loop) { player.setMediaTime (new Time (0)); player.start
* (); } return;
*/
if (buttonValues[0].isSelected()) {
if (fileName.size() == 0)
return;
index = (int) (Math.random() * fileName.size());
}
if (buttonValues[1].isSelected()) {
if (fileName.size() == 0)
return;// 必须有此if语句,否则当用户把播放列表清空的时候发生异常,偶然的机会发现的
// 现在感觉测试软件真是太重要了,看来以后程序做好后要反复测试,考虑各种情况
index = (index + 1) % fileName.size();
}
if (buttonValues[2].isSelected()) {
player.setMediaTime(new Time(0));
//startPlayer();
player.start();
}
createPlayer2();
}
}
}
private void exity_n() {
/*
* int exi;
* exi=JOptionPane.showConfirmDialog(this,"真的要离开么?","退出程序",JOptionPane.YES_NO_OPTION,
* JOptionPane.QUESTION_MESSAGE); //if(exi==null)
* if(exi==JOptionPane.YES_OPTION) { saveList(); System.exit(0); }
*
* return;
*/
saveList();
isWhile = false;
System.exit(0);
}
@SuppressWarnings("unchecked")
private void addList(String vf) {
// fileReadList=new fileReadList(fdd,)
// try
// {
// int i=0;
// fileName.addElement((fileName.size()+1)+"."+vf);
fileName.addElement(vf);
numList.addElement((numList.size() + 1) + "." + vf);
// fileName.addElement(++i+"."+vf);
dirName.addElement(title);
list.setListData(numList);
// }
/*
* catch(Exception e) { e.printStackTrace();
* //System.out.println(e.getMessage()); }
*/
}
private void pause(){
if(player!=null)
player.stop();
}
private void startCurrentPlayer(){
if(player!=null)
player.start();
}
@SuppressWarnings({ "deprecation", "unchecked" })
private void createPlayer2() {
try {
if(index == dirName.size()){
index = 0;
}
title = dirName.elementAt(index).toString();
}
// title=dirName.elementAt(index).toString();
catch (ArrayIndexOutOfBoundsException e) {
return;
}
file = new File(title);
closePreviosPlayer();// 关闭先前的媒体播放器
@SuppressWarnings("unused")
String extendName = "此播放器好象不支持"
+ title.substring(title.lastIndexOf(".") + 1) + "格式";
try {
player = Manager.createPlayer(file.toURL());// javax.media.Manager直接继承于java.lang.object,且它为final,不能被继承
player.addControllerListener(new ControllerHand());
player.start();
//startPlayer();
// list.setSelectedIndex(index);
list.setSelectedValue(numList.elementAt(index), true);
// list.setSelectionForeground(Color.blue);
// list.setSelectedIndex(index);
// addList(files);
setTitle(file.getName());
// addList("files");//到播放清单
} catch (Exception e) {
// JOptionPane.showMessageDialog(this,extendName,"出错了!!",JOptionPane.ERROR_MESSAGE);
// setTitle(extendName);
String ex = null;
try {
ex = fileName.elementAt(index).toString();
} catch (Exception e1) {
return;
}
fileName.removeElementAt(index);
numList.removeAllElements();
Enumeration enumFile = fileName.elements();
while (enumFile.hasMoreElements()) {
numList.addElement((numList.size() + 1) + "."
+ enumFile.nextElement());
}
dirName.removeElementAt(index);
// list.setListData(fileName);
list.setListData(numList);
System.out.println("已经从播放列表中删除 " + "\"" + ex + "\"" + " 文件,"
+ "因为此播放器不支持" + ex.substring(ex.lastIndexOf(".") + 1)
+ "格式," + "不过没有从硬盘真正删除");
if (numList.size() != 0) {
index %= numList.size();
createPlayer2();
}
}
}
private void saveList() {
Enumeration enumFile = fileName.elements();
Enumeration enumDir = dirName.elements();
try {
output = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(listFile)));
while (enumFile.hasMoreElements()) {
listWriteFile = new ListValues(enumFile.nextElement()
.toString(), enumDir.nextElement().toString());
output.writeObject(listWriteFile);
}
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
/*
* finally { output.flush();
* output.close();//郁闷,这两行不能写在这里,实在是一大遗憾啊,不知道有什么别的方法 }
*/
}
@SuppressWarnings("unchecked")
public void run() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
try {
if (!listFile.exists()) {
listFile.createNewFile();// 防止不存在此文件发生读取错误,这两行代码保证不存在的情况下自动建立
return;
}
input = new ObjectInputStream(new BufferedInputStream(
new FileInputStream(listFile)));
while (true) {
try {
listWriteFile = (ListValues) input.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
fileName.addElement(listWriteFile.getFileName());
numList.addElement((numList.size() + 1) + "."
+ listWriteFile.getFileName());
dirName.addElement(listWriteFile.getDirName());
}
} catch (EOFException e) {
try {
// if(!fileName.isEmpty())
input.close();// 确认有元素存在并加载完毕后关闭输入流
} catch (IOException e1) {
JOptionPane.showMessageDialog(MediaPlayer.this, "文件被非正常关闭",
"非法关闭", JOptionPane.ERROR_MESSAGE);
}
}
catch (IOException e) {
JOptionPane.showMessageDialog(MediaPlayer.this, "不能读取文件", "读取文件失败",
JOptionPane.ERROR_MESSAGE);
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
}
if (dirName.isEmpty())// 防止Vector越界
{
return;
}
index = (int) (Math.random() * (fileName.size()));// 产生随即数,进行随即播放
// if(36<fileName.size())
// index = 36;
list.setListData(numList);
// list.setListData(fileName);
// list.setSelectedValue(fileName.elementAt(index),true);
// list.ensureIndexIsVisible(index);//确保选择项可以看见
// list.setSelectionForeground(Color.green);
createPlayer2();
}
}
private void checkMenu(MouseEvent e) {
if (e.isPopupTrigger()) {
indexForDel = list.locationToIndex(e.getPoint());
int[] selected = { index, indexForDel };
// Point p=new Point(e.getX(),e.getY());
list.setSelectedIndices(selected);
popupMenu.show(list, e.getX(), e.getY());
}
// list.setSelectedIndex(index);
}
String reNames() throws ReName// 文件该名函数
{
String name = JOptionPane.showInputDialog(this, "请输入新的名字", fileName
.elementAt(indexForDel));
if (name == null || name.equals(""))
throw new ReName();
// 必须把name==null放在前面,否则会发生NullPointerExceptin,这个很好理解,
// 当我们按了取消后,name会成为空,那么name.equals("")就会发生异常
return name;
}
class ReName extends Exception// 自定义异常来处理文件该名的时候发生输入为空的情形
{
}
/*
* class Filters implements FilenameFilter { public boolean accept(File
* dir,String name) { return (name.endsWith(".exe")); } }
*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -