import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.File;
import java.net.URL;
import javax.media.*;
public class ExpVideoPlayer implements ControllerListener {
private Frame f;
private Panel panel;
private Player videoPlayer;
private Component visualPlayer; //视频
private Component controlPlayer= null; //控制条
private int videoWidth = 0; //视频宽
private int videoHeight = 0; //视频高
private int controlHeight = 30; //控制条高
private int insetWidth = 10; //间隔
private int insetHeight = 30;
URL urlFile=null;
public ExpVideoPlayer(URL url)
throws IOException,NoPlayerException,CannotRealizeException {
urlFile=url;
}
public ExpVideoPlayer(File file)
throws IOException,NoPlayerException,CannotRealizeException {
urlFile=file.toURL();
}
public ExpVideoPlayer(String filename)
throws IOException,NoPlayerException,CannotRealizeException {
File file=new File(filename);
urlFile=file.toURL();
}
public void play(){
f=new Frame("JMF 测试");
// 窗口关闭后,关闭播放器
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
if(videoPlayer!=null) {
videoPlayer.close();
}
System.exit(0);
}
});
f.setSize(500,400);
f.setVisible(true);
try {
//通过调用Manager的createPlayer方法来创建一个Player的对象
//这个对象是媒体播放的核心控制对象
videoPlayer=Manager.createPlayer(urlFile);
//让player对象进行相关的资源分配
videoPlayer.realize();
} catch (NoPlayerException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//对player对象注册监听器,能使其在相关事件发生的时候执行相关的动作
videoPlayer.addControllerListener(this);
}
//监听player的相关事件
public void controllerUpdate(ControllerEvent ce) {
if (ce instanceof RealizeCompleteEvent) {
//player实例化完成后进行player播放前预处理
videoPlayer.prefetch();
}else if(ce instanceof PrefetchCompleteEvent) {
if (visualPlayer != null)
return;
//取得player中的播放视频的组件,并得到视频窗口的大小
//然后把视频窗口的组件添加到Frame窗口中,
if ((visualPlayer=videoPlayer.getVisualComponent()) != null) {
Dimension size=visualPlayer.getPreferredSize();
videoWidth=size.width;
videoHeight=size.height;
f.add(visualPlayer,BorderLayout.CENTER);
} else {
videoWidth=320;
}
//取得player中的视频播放控制条组件,并把该组件添加到Frame窗口中
if ((controlPlayer=videoPlayer.getControlPanelComponent()) != null) {
controlHeight=controlPlayer.getPreferredSize().height;
f.add(controlPlayer,BorderLayout.SOUTH);
}
//设定Frame窗口的大小,使得满足视频文件的默认大小
f.setSize(videoWidth + insetWidth, videoHeight + controlHeight + insetHeight);
f.validate();
//启动视频播放组件开始播放
videoPlayer.start();
} else if (ce instanceof EndOfMediaEvent) {
//当播放视频完成后,把时间进度条恢复到开始,并再次重新开始播放
videoPlayer.setMediaTime(new Time(0));
videoPlayer.start();
}
}
public static void main(String[] args) {
try{
ExpVideoPlayer sp = new ExpVideoPlayer("F://1.mpg");
sp.play();
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}