Java简单实现视频录制播放功能

用Robot类,来连续截取屏幕图片,并通过JLabel连续加载图片,来实现一个视频录制的功能。

StartCapture.java类是主类,用来实现录制桌面图片的功能,以下是代码

package CountDown;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.JWindow;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import Util.FrameUtils;
import Util.UI;

public class StartCapture {
 JFrame frame = null;

 int WIDTH = 580;

 int HEIGHT = 290;

 JLabel titleLabel = null;
 JLabel timeLabel = null;
 JLabel currentTime = null;

 JWindow openFrame = null;
 JMenuBar bar = null;
 JMenu menu = null;
 JMenu menu2 = null;
 JMenu menu3 = null;
 
 JPanel panel = null;
 InnerTask it = new InnerTask();
 boolean isRecord = false; //视频是否正在录制
 
 Point startPoint = null;
 Point endPoint = null;
 JPanel windowPanel = null;
 JPanel panelRight = null;
 
 JToolBar stateBar = null;
 
 //++++++++++++++++++++++++++++++++++
 JList videoList = null;
 DefaultListModel listModel = null;
 JScrollPane scrollPane = null;
 //++++++++++++++++++++++++++++++++++
 
 public void initList(){
  listModel.clear();
  List list = CapUtils.getCaptureFolder();
  int length = list.size();
  //++++++++++++++++++++++++++++++++++++++
  
  for(int i=0;i<length;i++){
   listModel.addElement(" "+list.get(i));
  }
  
 }
 
 public StartCapture() {
  
  panelRight = new JPanel();
  
  
  listModel = new DefaultListModel();
  initList();
  
  videoList = new JList(listModel);
  videoList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
  videoList.setSelectedIndex(0);
  videoList.setVisibleRowCount(5);
  videoList.addMouseListener(new MouseAdapter(){

   @Override
   public void mouseClicked(MouseEvent e) {
//    if(e.getClickCount() == 2 && e.getButton() == 1){
//     String list = (String) listModel.get(videoList.getSelectedIndex());
//     new ShowCapture(CapUtils.URL+list.trim());
//    }
    if(e.getButton() == 3){
     int index = videoList.locationToIndex(e.getPoint());
     videoList.setSelectedIndex(index);
     JPopupMenu menu = new JPopupMenu("dddddd");
     JMenuItem item1 = new JMenuItem("播放");
     JMenuItem item3 = new JMenuItem("删除");
     menu.add(item1);
     menu.add(new JSeparator(SwingConstants.HORIZONTAL));
     menu.add(item3);
     menu.show(videoList, e.getX(), e.getY());
     item1.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
       if(listModel.getSize() !=0){
       String list = (String) listModel.get(videoList.getSelectedIndex());
       new ShowCapture(CapUtils.URL+list.trim());
       }
      }
     });
     item3.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
       if(listModel.getSize() !=0){
        int isDelete = JOptionPane.showConfirmDialog(frame, "是否删除录制的视频?", "删除", JOptionPane.YES_NO_OPTION);
        if(isDelete == 0){
         String list = (String) listModel.get(videoList.getSelectedIndex());
         File file = new File(CapUtils.URL+list.trim());
         File[] files = file.listFiles();
         for(int i = 0;i<files.length;i++){
          files[i].delete();
         }
         file.delete();
         listModel.remove(videoList.getSelectedIndex());
        }
        
       }
      }
     });
    }
   }
   
  });
  scrollPane = new JScrollPane(videoList);
  scrollPane.setPreferredSize(new Dimension(200,200));
  panelRight.add(scrollPane);
  
  //+++++++++++++++++++++++++++++++++++++++
  
  panel = new JPanel(new BorderLayout());
  frame = new JFrame("QNM录制");
  frame.setLayout(new BorderLayout());

  Font font = new Font("",Font.ITALIC,32);
  timeLabel = new JLabel();
  timeLabel.setFont(font);
  Font font2 = new Font("",Font.LAYOUT_RIGHT_TO_LEFT,32);
  titleLabel = new JLabel(" 距离本月发饷:");
  titleLabel.setFont(font2);
  Font font3 = new Font("",Font.PLAIN,32);
  currentTime = new JLabel("",JLabel.RIGHT);
  currentTime.setFont(font3);
  
  bar = new JMenuBar();
  menu = new JMenu("文件");
  menu2 = new JMenu("录制");
  menu3 = new JMenu("播放");
  bar.add(menu);
  bar.add(menu2);
  bar.add(menu3);

  JMenuItem item1 = new JMenuItem("打开目录");
  JMenuItem item2 = new JMenuItem("开始录制");
  JMenuItem item3 = new JMenuItem("停止录制");
  JMenuItem item4 = new JMenuItem("播放录制");
  menu.add(item1);
  menu2.add(item2);
  menu3.add(item4);
  menu2.add(new JSeparator(SwingConstants.HORIZONTAL));
  menu2.add(item3);
  
  
  
  stateBar = new JToolBar();
  stateBar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
  stateBar.setEnabled(false);
  stateBar.add(new JLabel(" 欢迎使用QNM系统"));
  frame.getContentPane().add(stateBar, BorderLayout.SOUTH);
  frame.getContentPane().add(bar, BorderLayout.NORTH);
  panel.add(currentTime, BorderLayout.SOUTH);
  panel.add(titleLabel, BorderLayout.NORTH);
  panel.add(timeLabel, BorderLayout.CENTER);
//  panel.add(currentTime);
//  panel.add(titleLabel);
//  panel.add(timeLabel);
  frame.add(panel,BorderLayout.CENTER);
  frame.add(panelRight,BorderLayout.WEST);
  frame.setBounds(FrameUtils.getSysLocation(WIDTH, HEIGHT));
  //frame.setUndecorated(true);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(3);
  //frame.setResizable(false);
  panel.addMouseListener(new MouseAdapter(){

   @Override
   public void mouseClicked(MouseEvent e) {
    if(e.getButton() == 3){
     JOptionPane.showMessageDialog(frame, "QNM系列");
    }
   }
   
  });
  
  item2.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
    it.startCapture();
   }
  });
  item3.addActionListener(new ActionListener(){
   
   public void actionPerformed(ActionEvent e) {
    it.stopCapture();
   }
   
  });
  item1.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
    String cmd = "cmd /c start "+CapUtils.URL;
    try {
     Runtime.getRuntime().exec(cmd);
    } catch (IOException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
    return;
   }
  });
  
  item4.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
    if(listModel.getSize() !=0){
     String list = (String) listModel.get(videoList.getSelectedIndex());
     new ShowCapture(CapUtils.URL+list.trim());
    }else{
     JOptionPane.showMessageDialog(frame, "未选中任何文件");
    }
    
   }
   
  });
  
  Timer timer = new Timer();
  TimerTask task = new TimerTask(){
   @Override
   public void run() {
    Calendar cal = Calendar.getInstance();
    
    Calendar cal2 = Calendar.getInstance();
    if(cal.get(Calendar.DATE)>=15){
     cal2.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, 15, 0, 0, 0);
    }else{
     cal2.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 15, 0, 0, 0);
    }
    long saveTime = cal2.getTimeInMillis() - cal.getTimeInMillis();
    long second = saveTime/1000;
    long minute = second/60;
    long hour = minute/60;
    
    long day = hour/24;
    
    long saveHour = (hour%24);
    long saveMinute = minute%60;
    long saveSecond = second%60;
    
    String saveStr = " "+day+"天"+saveHour+"小时"+saveMinute+"分钟"+saveSecond+"秒";
    
    cal.setTimeInMillis(System.currentTimeMillis());
    String time = cal.get(Calendar.YEAR) + "-"
      + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DATE)
      + " " + cal.get(Calendar.HOUR_OF_DAY)+":" +cal.get(Calendar.MINUTE)+":" +cal.get(Calendar.SECOND);
    timeLabel.setText(saveStr);
    currentTime.setText(time+" ");
    
    
    
   }
  };
  timer.schedule(task, 0, 500);
 }
 
 /**
  * 内部任务,用来展开视频录制的开始与停止的。
  * @author Administrator
  *
  */
 class InnerTask{
  Timer captureDeskTopTimer = null;
  TimerTask captureDeskTopTask = null;
  File folderFile = null;
  public void startCapture(){
   if(!isRecord){
    folderFile = new File(CapUtils.URL+System.currentTimeMillis());
    System.out.println(folderFile.getPath());
    if(!folderFile.isDirectory()){
     folderFile.mkdir();
    }
    System.out.println("正在录制");
    captureDeskTopTimer = new Timer();
    captureDeskTopTask = new TimerTask(){
     @Override
     public void run() {
      try {
       Robot ro = new Robot();
       BufferedImage bdi = ro.createScreenCapture(new Rectangle((int)FrameUtils.getScreenWidth(),(int)FrameUtils.getScreenHeight()));
       ImageIO.write(bdi, "jpg", new File(folderFile.getPath()+"\\"+System.currentTimeMillis()+".jpg"));
      } catch (AWTException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    };
    captureDeskTopTimer.schedule(captureDeskTopTask, 0, 40);
    isRecord = true;
   }
  }
  public void stopCapture(){
   if(isRecord){
    captureDeskTopTimer.cancel();
    isRecord = false;
    String newName = JOptionPane.showInputDialog(frame,"是否重命名录制的视频,为空则默认","重命名",JOptionPane.YES_NO_CANCEL_OPTION);
    if("".equals(newName)|| newName == null || "null".equals(newName)){
     listModel.addElement(" "+folderFile.getName());
     videoList.setSelectedValue(" "+folderFile.getName(), true);
    }else{
     File newFile = new File(CapUtils.URL+newName);
     folderFile.renameTo(newFile);
     listModel.addElement(" "+newName);
     videoList.setSelectedValue(" "+newName, true);
    }
   }
 }

 }
 public static void main(String[] args) {
  UI.setWindowStyle();
  new StartCapture();
 }
}




ShowCapture.java类,实现视频图片的播放

package CountDown;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import Util.FrameUtils;

import com.sun.awt.AWTUtilities;

public class ShowCapture {

	JFrame frame = null;
	int WIDTH = 500;
	int HEIGHT = 500;
	JLabel label = null;
	public ShowCapture(final String url) {
		frame = new JFrame();
		label = new JLabel();
		final Timer timer = new Timer();
		TimerTask task = new TimerTask(){

			File file = new File(url);
			File[] files = file.listFiles();
			final int size = files.length;
			int index = 0;
			@Override
			public void run() {
				if(index < size-1){
					label.setText("");
					Image image = Toolkit.getDefaultToolkit().getImage(files[index].getPath());
					ImageIcon icon = new ImageIcon();
					image = image.getScaledInstance((int)FrameUtils.getScreenWidth(),(int)FrameUtils.getScreenHeight(), Image.SCALE_FAST);
					icon.setImage(image);
					label.setIcon(icon);
					index++;
				}else{
					timer.cancel();
					frame.getContentPane().setBackground(Color.BLACK);
					AWTUtilities.setWindowOpacity(frame, 0.5f);
					frame.remove(label);
					JOptionPane.showMessageDialog(frame, " 播放完毕!");
					frame.dispose();
				}
			}
		};
		timer.schedule(task, 1000, 200);
		
		frame.setUndecorated(true);
		frame.add(label);
		frame.setBounds(0,0,(int)FrameUtils.getScreenWidth(),(int)FrameUtils.getScreenHeight());
		frame.setVisible(true);
		frame.setDefaultCloseOperation(3);
		frame.setResizable(false);
		
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		toolkit.addAWTEventListener(new AWTEventListener(){

			public void eventDispatched(AWTEvent event) {
				if(event.getClass()== KeyEvent.class){
					KeyEvent e = (KeyEvent) event;
					int key = e.getKeyCode();
					if(key == 27){
						timer.cancel();
						frame.dispose();
					}
				}
			}
			
		}, 1000);
	}
	
	
	public static void main(String[] args) {
		new ShowCapture("");
	}

}


还有两个工具类FrameUtils.java和UI.java

package Util;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Random;

import javax.swing.JDialog;
import javax.swing.JFrame;

public class FrameUtils {

	static Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
	
	static Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(
			GraphicsEnvironment.getLocalGraphicsEnvironment()
					.getLocalGraphicsEnvironment().getDefaultScreenDevice()
					.getDefaultConfiguration());

	/**
	 * 获得整个屏幕的宽度
	 * 
	 * @return
	 */
	public static double getScreenWidth() {
		return screen.getWidth();
	}

	/**
	 * 获得整个屏幕的高度
	 * 
	 * @return
	 */
	public static double getScreenHeight() {
		return screen.getHeight();
	}

	/**
	 * 获得程序在屏幕中间的位置
	 * 
	 * @param WIDTH
	 *            程序的宽度
	 * @param HEIGHT
	 *            程序的高度
	 * @return Rectangle
	 */
	public static Rectangle getSysLocation(int WIDTH, int HEIGHT) {
		Rectangle rectangle = new Rectangle();
		rectangle.setLocation((int) (getScreenWidth() - WIDTH) / 2,
				(int) (getScreenHeight() - HEIGHT) / 2);
		rectangle.setSize(WIDTH, HEIGHT);
		return rectangle;
	}
	
	/**
	 * 获得程序在屏幕右下角的位置
	 * 
	 * @param WIDTH
	 *            程序的宽度
	 * @param HEIGHT
	 *            程序的高度
	 * @return Rectangle
	 */
	public static Rectangle getRDLocation(int WIDTH, int HEIGHT) {
		Rectangle rectangle = new Rectangle();
		rectangle.setLocation((int) (getScreenWidth() - WIDTH),
				(int) (getScreenHeight() - HEIGHT - insets.bottom));
		rectangle.setSize(WIDTH, HEIGHT);
		return rectangle;
	}

	public static void confirm(Frame frame) {
		JDialog dialog = new JDialog(frame, true);
		dialog.setBackground(Color.white);
		int width = 100;
		int height = 100;
		dialog.setBounds((int) (getScreenWidth() - width) / 2,
				(int) (getScreenHeight() - height) / 2, width, height);
		dialog.setTitle("ffffffff");
		dialog.setVisible(true);
	}

	static Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();

	/**
	 * 向系统粘贴板中写入字符串
	 * 
	 * @param temp
	 *            要写入的字符串
	 */
	public static void storeClipString(String temp) {
		StringSelection stringSelection = new StringSelection(temp);
		sysClip.setContents(stringSelection, null);

	}

	/**
	 * 读取系统粘贴板中的字符串
	 * 
	 * @return
	 */
	public static String readClipString() {
		String temp = "";
		try {
			temp = (String) sysClip.getData(DataFlavor.stringFlavor);
		} catch (UnsupportedFlavorException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp;
	}

	public static void shakeWindow(JFrame frame){
		Rectangle currentRect = new Rectangle();
		currentRect.setLocation(frame.getLocation());
		currentRect.setSize(frame.getSize());
		for (int i = 0; i < 5; i++) {
			Random random = new Random();
			int raint = (int) (random.nextFloat() * 10);
			int newPointX = currentRect.getLocation().x + raint;
			int newPointY = currentRect.getLocation().y + raint;
			;
			frame.setBounds(newPointX, newPointY, currentRect.getSize().width, currentRect.getSize().height);
			frame.setVisible(true);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
	}

}

package Util;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class UI {

	public static void setWindowStyle() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
	}

	public static void setOtherStyle() {
		try {
			UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
	}

}





注:界面效果图


功能简单


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值