java mplayer 源码_师兄写的一个JAVA播放器的源代码
MediaPlayer.java
----------------------------------------------------------------------------
//程序主文件
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.*;
import java.io.*;
import java.util.*;//為了導入Vector
//import com.sun.java.swing.plaf.windows.*;
public class MediaPlayer extends JFrame implements ActionListener,Runnable
{
private JMenuBar????????? bar;//菜單條
private JMenu???????????? fileMenu,choiceMenu,aboutMenu;
private JMenuItem???????? openItem,openDirItem,closeItem,about,infor;
private JCheckBoxMenuItem onTop;
private boolean?????????? top=false,loop;//設定窗口是否在最前面
private Player??????????? player;//Play是個實現Controller的接口
private File????????????? file,listFile;//利用File類結合JFileChooser進行文件打開操作,后則與list.ini有關
private Container???????? c;
//private UIManager.LookAndFeelInfo[] look;
private String??????????? title,listIniAddress;//標題
private FileDialog??????? fd;
private JPanel??????????? panel,panelSouth;
private Icon????????????? icon; //開始進入的時候要顯示的圖標,它為抽象類,不能自己創建
private JLabel??????????? label,listB;//用來顯示圖標
private JList???????????? list;//播放清單
private JScrollPane?????? scroll;//使播放清單具有滾動功能
private ListValues??????? listWriteFile;//用于向文件中讀取對象
private ObjectInputStream input;//對象輸入流
private ObjectOutputStream output;//對象輸出流
private JPopupMenu??????? popupMenu;//鼠標右鍵彈出菜單
private JMenuItem???????? del,delAll,reName;????? //彈出菜單顯示的菜單項,包括刪除,全部刪除和重命名
private Vector??????????? fileName,dirName,numList;
private String??????????? files,dir;
private int?????????????? index;//曲目指針
private Properties??????? prop;//獲得系統屬性
private int?????????????? indexForDel;//標志要刪除的列表項目的索引
private ButtonGroup?????? buttonGroup;//控制按鈕組
private JRadioButtonMenuItem[]??? buttonValues;
private String[]????????? content={"隨機播放","順序播放","單曲循環"};
private DialogDemo??????? dialog1;
//private JDialogTest?????? dialog2;//用于顯示播放清單
MediaPlayer()//構造函數
{
super("java音頻播放器1.1版");//窗口標題
c=getContentPane();
c.setLayout(new BorderLayout());
//c.setBackground(new Color(40,40,95));
fileName=new Vector(1);
dirName=new Vector(1);
numList=new Vector(1);//構造三個容器用于支持播放清單
//vectorToString=new String[];
//prop=new Properties(System.getProperties());
//listIniAddress=prop.getProperty("user.dir")+"\\list.ini";
//listFile=new File(listIniAddress);//本來這些代碼用來取的系統屬性,后來
//發現根本就不用這么麻煩
listFile=new File("list.ini");//直接存于此目錄
Thread readToList=new Thread(this);//注意編線程程序的時候要注意運行的時候含有的變量億定義或者初始化,
//這就要求線程要等上述所說的情況下再運行,否則很容易發生錯誤或則異常
list=new JList();
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setSelectionForeground(new Color(0,150,150));
list.setVisibleRowCount(10);
list.setFixedCellHeight(12);
list.setFixedCellWidth(250);
list.setFont(new Font("Serif",Font.PLAIN,12));
list.setBackground(new Color(40,40,95));
list.setForeground(new Color(0,128,255));
//list.setOpaque(false);
list.setToolTipText("點右鍵顯示更多功能");//創建播放清單并設置各個屬性
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2) //判斷是否雙擊
{
index = list.locationToIndex(e.getPoint());//將鼠標坐標轉化成list中的選項指針
createPlayer2();
//System.out.println("Double clicked on Item " + index);,此是測試的時候加的
}
}
/* public void mousePressed(MouseEvent e)
{
checkMenu(e);//自定義函數,判斷是否是右鍵,來決定是否顯示菜單
}*/
public void mouseReleased(MouseEvent e)
{
checkMenu(e);//與上面的一樣,判斷是否鼠標右鍵
}
}
);
//listB=new JLabel(new ImageIcon("qingdan.gif"),SwingConstants.CENTER);
scroll=new JScrollPane(list);//用于存放播放列表
//dialog2=new JDialogTest(MediaPlayer.this,"播放清單",scroll);
//dialog2.setVisible(true);
readToList.start();//啟動先程,加載播放列表
try
{
Thread.sleep(10);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
/*look=UIManager.getInstalledLookAndFeels();
try
{
UIManager.setLookAndFeel(look[2].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception e)
{
e.printStackTrace();
}*///與下面的代碼實現相同的功能,但執行速度要慢,原因:明顯轉了個大彎
/*try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
e.printStackTrace();
} *///此段代碼使執行速度大大降低
bar=new JMenuBar();
setJMenuBar(bar);//此兩行創建菜單欄并放到此窗口程序
//bar.setBackground(new Color(48,91,183));
fileMenu=new JMenu("文件");
bar.add(fileMenu);
choiceMenu=new JMenu("控制");
bar.add(choiceMenu);
aboutMenu=new JMenu("幫助");
bar.add(aboutMenu);
openItem??? =new JMenuItem("打開文件");
openDirItem =new JMenuItem("打開目錄");
closeItem?? =new JMenuItem("退出程序");
openItem.addActionListener(this);
openDirItem.addActionListener(this);
closeItem.addActionListener(this);
fileMenu.add(openItem);
fileMenu.add(openDirItem);
fileMenu.add(closeItem);
onTop=new JCheckBoxMenuItem("播放時位于最前面",top);
choiceMenu.add(onTop);
onTop.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(onTop.isSelected())
top=true;
else top=false;
setAlwaysOnTop(top);
}
}
);
choiceMenu.addSeparator();//加分割符號
buttonGroup=new ButtonGroup();
buttonValues=new JRadioButtonMenuItem[3];
for(int bt=0;bt<3;bt++)
{
buttonValues[bt]=new JRadioButtonMenuItem(content[bt]);
buttonGroup.add(buttonValues[bt]);
choiceMenu.add(buttonValues[bt]);
}
buttonValues[0].setSelected(true);
choiceMenu.addSeparator();
/*loopItem=new JCheckBoxMenuItem("是否循環");
choiceMenu.add(loopItem);
loopItem.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
loop=!loop;
}
}
);*/
infor=new JMenuItem("軟件簡介");
aboutMenu.add(infor);
infor.addActionListener(this);
about=new JMenuItem("關于作者");
about.addActionListener(this);
aboutMenu.add(about);
//菜單欄設置完畢
panel=new JPanel();
panel.setLayout(new BorderLayout());
c.add(panel,BorderLayout.CENTER);
panelSouth=new JPanel();
panelSouth.setLayout(new BorderLayout());
c.add(panelSouth,BorderLayout.SOUTH);
icon=new? ImageIcon("icon\\Player.jpg");
label=new JLabel(icon);
panel.add(label);
popupMenu=new JPopupMenu();
del????? =new JMenuItem("刪除");//鼠標右鍵彈出菜單對象實例化
popupMenu.add(del);
del.addActionListener(this);
delAll?? =new JMenuItem("全部刪除");
popupMenu.add(delAll);
delAll.addActionListener(this);
reName?? =new JMenuItem("重命名");
popupMenu.add(reName);
reName.addActionListener(this);
scroll=new JScrollPane(list);//用于存放播放列表
listB=new JLabel(new ImageIcon("icon\\qingdan.gif"),SwingConstants.CENTER);
panelSouth.add(listB,BorderLayout.NORTH);
panelSouth.add(scroll,BorderLayout.CENTER);
dialog1=new DialogDemo(MediaPlayer.this,"軟件說明");
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//設定窗口關閉方式
//this.setTitle("d");編譯通過,說明可以再次設定標題
this.setLocation(400,250);//設定窗口出現的位置
//this.setSize(350,320);//窗口大小
setSize(350,330);
this.setResizable(false);//設置播放器不能隨便調大小
this.setVisible(true);//此句不可少,否則窗口會不顯示
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==openItem)//getSource()判斷發生時間的組鍵
{
//System.out.println("d");測試用
openFile();
//createPlayer();
//setTitle(title);
}
if(e.getSource()==openDirItem)//打開目錄
{
openDir();
}
if(e.getSource()==closeItem)//推出播放器
{
exity_n();
//System.exit(0);
}
if(e.getSource()==about)
{
JOptionPane.showMessageDialog(this,"此簡易播放器由計科0302\n"
+"harly\n? "+"??????? 完成??????????? ",
"參與者",
JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource()==del)
{
//index
//delPaintList(index);
fileName.removeElementAt(indexForDel);
dirName.removeElementAt(indexForDel);
numList.removeAllElements();//從三個容器里面移除此項
Enumeration enumFile=fileName.elements();
while(enumFile.hasMoreElements())
{
numList.addElement((numList.size()+1)+"."+enumFile.nextElement());
//numList添加元素,顯示播放里表中
}
//list.setListData(fileName);
list.setListData(numList);
if(index
list.setSelectedValue(numList.elementAt(index),true);
else
{
if(index==indexForDel);
else
if(index!=0)
list.setSelectedValue(numList.elementAt(index-1),true);
}
//list.setSelectedIndex(index);
}
if(e.getSource()==delAll)//全部刪除
{
fileName.removeAllElements();
dirName.removeAllElements();
numList.removeAllElements();
list.setListData(numList);
}
if(e.getSource()==reName)//重命名
{
String name;//=JOptionPane.showInputDialog(this,"請輸入新的名字");
try
{
name=reNames();
fileName.setElementAt(name,indexForDel);
numList.setElementAt((indexForDel+1)+"."+name,indexForDel);
}
catch(ReName e2)//自定義的異常
{
}
}
if(e.getSource()==infor)
{
dialog1.setVisible(true);
}
}
public static void main(String[] args)
{
final MediaPlayer mp=new MediaPlayer();
mp.setIconImage(new ImageIcon("icon\\mPlayer.jpg").getImage());//改變默認圖標
mp.addWindowListener(new WindowAdapter()//注冊窗口事件
{
public void windowClosing(WindowEvent e)
{
//System.exit(0);
mp.exity_n();
}
}
);
System.out.println("注意:更新文件列表后,請先正常關閉播放器"
+"\n然后再關閉此DOS窗口,否則導致播放列表不能保存!!");
}
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;//缺少此句如果第一次打開文件的時候取消操作的時候第二次也不能打開文件了
//}
}
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
{
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
{
System.out.println(ss[i]);
}
}*/
}
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());
player.start();
addList(files);
index=fileName.size()-1;
list.setSelectedValue(numList.elementAt(index),true);
//list.setSelectedIndex(index);
//list.setSelectionForeground(Color.blue);
setTitle(title);
//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));
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();
System.exit(0);
}
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 createPlayer2()
{
try{title=dirName.elementAt(index).toString();}
//title=dirName.elementAt(index).toString();
catch(ArrayIndexOutOfBoundsException e)
{return;}
file=new File(title);
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());
player.start();
//list.setSelectedIndex(index);
list.setSelectedValue(numList.elementAt(index),true);
//list.setSelectionForeground(Color.blue);
//list.setSelectedIndex(index);
//addList(files);
setTitle(title);
//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();//郁悶,這兩行不能寫在這里,實在是一大遺憾啊,不知道有什么別的方法
}*/
}
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)
{
listWriteFile=(ListValues)input.readObject();
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(ClassNotFoundException e)
{
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()));//產生隨即數,進行隨即播放
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"));
}
}*/
}
總結
以上是生活随笔為你收集整理的java mplayer 源码_师兄写的一个JAVA播放器的源代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 连江县凤城镇邮编
- 下一篇: mediawiki java_使用Med