java视频格式转换代码

时间:2021-02-02 09:10:09

http://blog.163.com/zzf_fly/blog/static/20958915820127217443816/

package com.gkzx.online.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

/*
 * Title:FLV视频转换类
 * @author 郑忠飞
 * 2012-08-21
 */

public class Conver {
 
 
 private Date dt;
 private long begintime;
 private String PATH;
 private String filerealname; // 文件名 不包括扩展名
 private String filename; // 包括扩展名
 private String videofolder = null; // 别的格式视频的目录
 private String flvfolder = null;// 转化为flv视频的存放目录
 private final static String FFMPEGPATH = "/DownLoad/ffmpeg"; // ffmpeg.exe的目录
 private final static String MENCODERPATH = "/DownLoad"; // ffmpeg.exe的目录

// private String videoRealPath = "D:/ffmpeg/flv/"; // 截图的视频目录;
 // private String imageRealPath = "D:/ffmpeg/img/"; // 截图的存放目录
 public Conver(String otherpath,String flvpath){
  this.PATH = otherpath;//其他类型的视频文件文件夹
  this.flvfolder = flvpath;//转换成为flv的格式之后视频存放的路径
 }
 /**
  * 对视频格式进行转换
  *
  * @author 郑忠飞 2012-08-21
  */
 public boolean beginConver() {
  File fi = new File(PATH);
  filename = fi.getName();
  filerealname = filename.substring(0, filename.lastIndexOf("."))
    .toLowerCase();
  String videofolderTemp = PATH.substring(0,PATH.lastIndexOf("\\"));
  videofolder = videofolderTemp.replace("flash", "other");
  System.out.println("----接收到文件(" + PATH
    + ")需要转换-------------------------- \n");
  if (!checkfile(PATH)) {
   System.out.println(PATH + "文件不存在" + " ");
   return false;
  }
  dt = new Date();
  begintime = dt.getTime();
  System.out.println("----开始转文件(" + PATH
    + ")-------------------------- \n");
  if (process()) {
   Date dt2 = new Date();
   System.out.println("转换成功 \n");
   long endtime = dt2.getTime();
   long timecha = (endtime - begintime);
   String totaltime = sumTime(timecha);
   System.out.println("共用了:" + totaltime + " ");
   /*
    * if(processImg()) { Conver.OutShowLog.append("截图成功了 \n"); }else {
    * Conver.OutShowLog.append("截图不成功了 "); }
    */
   PATH = null;
   return true;
  } else {
   PATH = null;
   return false;
  }
 }

/**
  * 检查文件时否存在
  *
  * @param path
  * @return
  */
 private boolean checkfile(String path) {
  File file = new File(path);
  if (!file.isFile()) {
   return false;
  } else {
   return true;
  }
 }

/**
  * 计算视频转换总时间
  */
 public String sumTime(long ms) {
  int ss = 1000;
  long mi = ss * 60;
  long hh = mi * 60;
  long dd = hh * 24;

long day = ms / dd;
  long hour = (ms - day * dd) / hh;
  long minute = (ms - day * dd - hour * hh) / mi;
  long second = (ms - day * dd - hour * hh - minute * mi) / ss;
  long milliSecond = ms - day * dd - hour * hh - minute * mi - second
    * ss;

String strDay = day < 10 ? "0" + day + "天" : "" + day + "天";
  String strHour = hour < 10 ? "0" + hour + "/小时" : "" + hour + "小时";
  String strMinute = minute < 10 ? "0" + minute + "分" : "" + minute + "分";
  String strSecond = second < 10 ? "0" + second + "秒" : "" + second + "秒";
  String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : ""
    + milliSecond;
  strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond + "毫秒" : ""
    + strMilliSecond + " 毫秒";
  return strDay + strHour + ":" + strMinute + ":" + strSecond + " "
    + strMilliSecond;

}

private boolean process() {
  int type = checkContentType();
  boolean status = false;
  if (type == 0) { // 如果视频的格式ffmpag可以直接转换
   status = processFLV(PATH); // 直接将文件转为flv文件
  } else if (type == 1) {
   String avifilepath = processAVI(type);
   if (avifilepath == null)
    return false;
   // avi文件没有得到
   else {
    System.out.println("开始转换");
    status = processFLV(avifilepath);// 将avi转为flv
   }
  }
  return status;
 }

/**
  * 检查视频的格式 方法说明:如果视频的格式可以直接转换那么返回为0; 如果视频的格式不可以转换那么返回为1;
  */
 private int checkContentType() {
  String type = PATH.substring(PATH.lastIndexOf(".") + 1, PATH.length())
    .toLowerCase();
  // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
  if (type.equals("avi")) {
   return 0;
  } else if (type.equals("mpg")) {
   return 0;
  } else if (type.equals("wmv")) {
   return 0;
  } else if (type.equals("3gp")) {
   return 0;
  } else if (type.equals("mov")) {
   return 0;
  } else if (type.equals("mp4")) {
   return 0;
  } else if (type.equals("asf")) {
   return 0;
  } else if (type.equals("asx")) {
   return 0;
  } else if (type.equals("flv")) {
   return 0;
  }
  // 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),
  // 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
  else if (type.equals("wmv9")) {
   return 1;
  } else if (type.equals("rm")) {
   return 1;
  } else if (type.equals("rmvb")) {
   return 1;
  }
  return 9;
 }

// 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.
 @SuppressWarnings({ "deprecation", "unchecked" })
 private String processAVI(int type) {
  String mencoderEXEDir = ServletActionContext.getRequest().getRealPath(MENCODERPATH)
    + File.separator + "mencoder.exe";;
  List commend = new java.util.ArrayList();
  commend.add(mencoderEXEDir);
  commend.add(PATH);
  commend.add("-oac");
  commend.add("mp3lame");
  commend.add("-lameopts");
  commend.add("preset=64");
  commend.add("-ovc");
  commend.add("xvid");
  commend.add("-xvidencopts");
  commend.add("bitrate=600");
  commend.add("-of");
  commend.add("avi");
  commend.add("-o");
  commend.add(videofolder +"\\"+ filerealname + ".avi");
  try {
   ProcessBuilder builder = new ProcessBuilder();
   builder.command(commend);
   Process p = builder.start();

doWaitFor(p);
   return videofolder + "\\" +filerealname + ".avi";
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
 }

// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
 @SuppressWarnings({ "unchecked", "deprecation" })
 private boolean processFLV(String oldfilepath) {
  //ffmpeg.exe的位置
  String videoEXEDir = ServletActionContext.getRequest().getRealPath(
    FFMPEGPATH)
    + File.separator + "ffmpeg.exe";
  if (!checkfile(PATH)) {
   System.out.println(oldfilepath + " is not file");
   return false;
  }

List commend = new java.util.ArrayList();
  commend.add(videoEXEDir);
  commend.add("-i");
  commend.add(oldfilepath);
  commend.add("-ab");
  commend.add("128");
  commend.add("-acodec");
  commend.add("libmp3lame");
  commend.add("-ac");
  commend.add("1");
  commend.add("-ar");
  commend.add("22050");
  commend.add("-r");
  commend.add("29.97");
  commend.add("-b");
  commend.add("521");
  commend.add("-y");
  commend.add(flvfolder + "\\" +filerealname + ".flv");
  // 低品质:ffmpeg -i infile -ab 128 -acodec libmp3lame -ac 1 -ar 22050 -r
  // 29.97 -b 512 -y outfile

try {
   ProcessBuilder builder = new ProcessBuilder();
   builder.command(commend);
   // builder.redirectErrorStream(true);
   Process p = builder.start();
   doWaitFor(p);
   p.destroy();
   deleteFile(oldfilepath);
   return true;
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  }
 }

@SuppressWarnings("static-access")
 public int doWaitFor(Process p)

{
  InputStream in = null;
  InputStream err = null;
  int exitValue = -1; // returned to caller when p is finished
  try {
   System.out.println("comeing");
   in = p.getInputStream();
   err = p.getErrorStream();
   boolean finished = false; // Set to true when p is finished

while (!finished) {
    try {
     while (in.available() > 0) {
      // Print the output of our system call
      Character c = new Character((char) in.read());
      System.out.print(c);//使用缓存技术
     }
     while (err.available() > 0) {
      // Print the output of our system call
      Character c = new Character((char) err.read());
      System.out.print(c);
     }

// Ask the process for its exitValue. If the process
     // is not finished, an IllegalThreadStateException
     // is thrown. If it is finished, we fall through and
     // the variable finished is set to true.
     exitValue = p.exitValue();
     finished = true;

} catch (IllegalThreadStateException e) {
     // Process is not finished yet;
     // Sleep a little to save on CPU cycles
     Thread.currentThread().sleep(500);
    }
   }
  } catch (Exception e) {
   // unexpected exception! print it out for debugging...
   System.err.println("doWaitFor();: unexpected exception - "
     + e.getMessage());
  } finally {
   try {
    if (in != null) {
     in.close();
    }

} catch (IOException e) {
    System.out.println(e.getMessage());
   }
   if (err != null) {
    try {
     err.close();
    } catch (IOException e) {
     System.out.println(e.getMessage());
    }
   }
  }
  // return completion status to caller
  return exitValue;
 }

/**
  * 删除文件
  *
  * @param filepath
  */
 public void deleteFile(String filepath) {
  File file = new File(filepath);
  if (PATH.equals(filepath)) {
   if (file.delete()) {
    System.out.println("文件" + filepath + "已删除");
   }
  } else {
   if (file.delete()) {
    System.out.println("文件" + filepath + "已删除 ");
   }
   File filedelete2 = new File(PATH);
   if (filedelete2.delete()) {
    System.out.println("文件" + PATH + "已删除");
   }
  }
 }
}