Java calls ffmpeg to convert video formats to flv and ffmpegflv
Java calls ffmpeg to convert the video format to flv
Note: The following program runs in Linux. If rmvb is converted to avi in windows, the problem may occur. To succeed, you need to download the next drv43260.dll and put it under C: WindowsSystem32.
Writing a video management system over the past few days has encountered a major problem: If you convert different formats to flv, format! After some searching on the internet, I am summing up, sorting out, and finally finishing it! This allows you to convert videos and delete original files!
The main principle of format conversion is to first use java to call ffmpeg's exe file!
However, some formats cannot be processed by ffmpeg, such as rmvb. In this way, you can first call mencoder to convert the format to avi and then convert it to flv!
I mainly write three classes: Conver. java
ConverBegin. Java ConverVideo. java
The Conver. java code is as follows:
Package org. conver; import java. awt. borderLayout; import javax. swing. JFrame; import javax. swing. JScrollPane; import javax. swing. JTextArea; @ SuppressWarnings ("serial") public class Conver extends JFrame {public static JTextArea OutShowLog; public Conver () {setTitle ("FLV conversion"); setSize (500,400 ); setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE); OutShowLog = new JTextArea (); JScrollPane OutPane = newJScrollPane (OutShowLog); add (OutPane, BorderLayout. CENTER); setVisible (true);} public static void main (String args []) {new Conver (); ConverBegin cb = new ConverBegin (); cb. start ();}}
The ConverBegin. java code is as follows:
Package org. conver; import java. io. file; public class ConverBegin extends Thread {String [] ff; public void run () {while (true) {String folderpath = "other/"; // String path = null; file f = newFile (folderpath); if (f. isDirectory () {ff = f. list (); int I = 0; while (I <ff. length) {new ConverVideo (folderpath + ff [I]). beginConver (); I ++;} Conver. outShowLog. append ("--------------- converted in total" + ff. length + "----------- video ------------"); ff = null;} f = null; try {Thread. sleep (10000);} catch (InterruptedExceptione) {// If the thread fails to restart this. start ();}}}}
The ConverBegin. java code is as follows:
Package org. conver; import java. io. file; import java. io. IOException; import java. io. inputStream; import java. util. date; import java. util. list; public class ConverVideo {private Date dt; private long begintime; private String PATH; private String filerealname; // the file name does not include the private Stringfilename extension; // include the extension private String videofolder = "other/"; // private String flvfolder = "flv/"; // privateStr Ingffmpegpath = "ffmpeg/ffmpeg.exe"; // privateStringmencoderpath = "ffmpeg/mencoder"; // privateStringvideoRealPath = "flv/"; // video directory; privateString imageRealPath = "img/"; // storage directory // privateString batrealpath = "ffmpeg/ffmpeg. bat "; // bat directory publicConverVideo () {} public ConverVideo (String path) {PATH = path;} publicString getPATH () {return PATH;} public void setPATH (String path) {PA TH = path;} public boolean beginConver () {File fi = new File (PATH); filename = fi. getName (); filerealname = filename. substring (0, filename. lastIndexOf (". ")). toLowerCase (); Conver. outShowLog. append ("---- received file (" + PATH + ") needs to be converted ------------------------"); if (! Checkfile (PATH) {Conver. outShowLog. append (PATH + "file does not exist" + ""); return false;} dt = new Date (); begintime = dt. getTime (); Conver. outShowLog. append ("---- start file conversion (" + PATH + ") --------------------------"); if (process () {Date dt2 = new Date (); Conver. outShowLog. append ("converted"); long endtime = dt2.getTime (); long timecha = (endtime-begintime); String totaltime = sumTime (timecha); Conver. outShowLog. append ("Total "+ Totaltime +" "); if (processImg () {Conver. outShowLog. append ("succeeded");} else {Conver. outShowLog. append ("failed");} PATH = null; return true;} else {PATH = null; return false;} public boolean processImg () {// System. out. println (newfilename + "->" + newimg); List commend = new java. util. arrayList (); commend. add (ffmpegpath); commend. add ("-I"); commend. add (videoRealPath + filerealname + ". flv "); co Mmend. add ("-y"); commend. add ("-f"); commend. add ("image2"); commend. add ("-ss"); commend. add ("38"); commend. add ("-t"); commend. add ("0.001"); commend. add ("-s"); commend. add ("320x240"); commend. add (imageRealPath + filerealname + ". jpg "); try {ProcessBuilder builder = new ProcessBuilder (); builder. command (commend); builder. start (); return true;} catch (Exception e) {e. printStackTrace (); return false ;}} Private boolean process () {int type = checkContentType (); boolean status = false; if (type = 0) {// status = processFLV (PATH ); // directly convert the file to the flv File status = processFLV (PATH);} else if (type = 1) {String avifilepath = processAVI (type); if (avifilepath = null) returnfalse; // The avi file does not get else {System. out. println ("kaishizhuang"); status = processFLV (avifilepath); // convert avi to flv} return status;} private I Nt checkContentType () {String type = PATH. substring (PATH. lastIndexOf (". ") + 1, PATH. length ()). toLowerCase (); // formats that can be parsed by ffmpeg: (asx, asf, mpg, wmv, 3gp, mp4, mov, avi, flv, etc.) 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;} // format of files that cannot be parsed by ffmpeg (wmv9, rm, rmvb, etc.). // you can use other tools (mencoder) first) convert to avi (which can be parsed by ffmpeg) format. else if (type. equals ("wmv9") {return 1;} else if (type. equals ("rm") {return 1;} else if (type. equals ("rmvb") {return 1;} return 9;} private boolean checkfile (String pa Th) {File file = new File (path); if (! File. isFile () {return false;} else {return true ;}// formats of files that cannot be parsed by ffmpeg (wmv9, rm, rmvb, etc ), you can use other tools (mencoder) to convert to avi (which can be parsed by ffmpeg) format. private String processAVI (int type) {List commend = new java. util. arrayList (); commend. add (mencoderpath); 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 "); // command type: mencoder 1. rmvb-oac mp3lame-lameoptspreset = 64-ovc xvid //-xvidencopts bitrate = 600-of avi-ormvb. avi try {ProcessBuilder builder = newProcessBuilder (); builder. command (commend); Process p = builder. start (); doWaitFor (p); return vid Eofolder + filerealname + ". avi ";} catch (Exception e) {e. printStackTrace (); return null ;}// formats that can be parsed by ffmpeg: (asx, asf, mpg, wmv, 3gp, mp4, mov, avi, flv, etc) private boolean processFLV (String oldfilepath) {if (! Checkfile (PATH) {System. out. println (oldfilepath + "is not file"); return false;} List commend = new java. util. arrayList (); commend. add (ffmpegpath); commend. add ("-I"); commend. add (oldfilepath); commend. add ("-AB"); commend. add ("64"); commend. add ("-acodec"); commend. add ("mp3"); commend. add ("-ac"); commend. add ("2"); commend. add ("-ar"); commend. add ("22050"); commend. add ("-B"); commend. add ("230"); com Mend. add ("-r"); commend. add ("24"); commend. add ("-y"); commend. add (flvfolder + filerealname + ". flv "); try {ProcessBuilder builder = newProcessBuilder (); String cmd = commend. toString (); 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;} Public int doWaitFor (Process p) {InputStream in = null; InputStream err = null; int exitValue =-1; // returned to caller when pis 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! Printit 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;} public void deleteFile (String filepath) {File file = new File (filepath); if (PATH. equals (filepath) {if (file. delete () {System. out. println ("file" + filepath + "deleted") ;}} else {if (file. delete () {System. out. println ("file" + filepath + "deleted");} F Ile filedelete2 = newFile (PATH); if (filedelete2.delete () {System. out. println ("file" + PATH + "deleted") ;}} 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": "" + day + "day"; String strHour = hour <10? "0" + hour + "hour": "" + hour + "hour"; String strMinute = minute <10? "0" + minute + "points": "" + minute + "points"; String strSecond = second <10? "0" + second + "second": "" + second + "second"; String strMilliSecond = milliSecond <10? "0" + milliSecond: "" + milliSecond; strMilliSecond = milliSecond <100? "0" + strMilliSecond + "millisecond": "" + strMilliSecond + "millisecond"; return strDay + "" + strHour + ":" + strMinute + ": "+ strSecond +" "+ strMilliSecond ;}}
If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!