详解java调用ffmpeg转换视频格式为flv
详解java调用ffmpeg转换视频格式为flv
注意:下面的程序是在Linux下运行的,如果在windows下rmvb转换成avi会出现问题,想成功需要下载下个drv43260.dll东西放到C:WindowsSystem32下面
这几天在写一个视频管理系统,遇到一个很大的问题就是如果把不同格式转换为flv,格式!经过网上的一番搜索,自己在总结,整理,整理,终于整出来了!实现了视频进行转换的同时还能够进行视频截图和删除原文件的功能!
格式转换主要原理就是先用java调用ffmpeg的exe文件!
但是有些格式是ffmpeg不能处理的比如rmvb,这样的可以先调用mencoder先把格式转换为avi再进行转换为flv!
我主要写3个类:分别为Conver.java
ConverBegin.Java ConverVideo.java
Conver.java 代码如下:
packageorg.Conver; importjava.awt.BorderLayout; importjavax.swing.JFrame; importjavax.swing.JScrollPane; importjavax.swing.JTextArea; @SuppressWarnings("serial") publicclassConverextendsJFrame{ publicstaticJTextAreaOutShowLog; publicConver(){ setTitle("FLV转换"); setSize(500,400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); OutShowLog=newJTextArea(); JScrollPaneOutPane=newJScrollPane(OutShowLog); add(OutPane,BorderLayout.CENTER); setVisible(true); } publicstaticvoidmain(Stringargs[]){ newConver(); ConverBegincb=newConverBegin(); cb.start(); } }
ConverBegin.java 代码如下:
packageorg.Conver; importjava.io.File; publicclassConverBeginextendsThread{ String[]ff; publicvoidrun(){ while(true){ Stringfolderpath="other/"; //Stringpath=null; Filef=newFile(folderpath); if(f.isDirectory()){ ff=f.list(); inti=0; while(iConverBegin.java代码如下
packageorg.Conver; importjava.io.File; importjava.io.IOException; importjava.io.InputStream; importjava.util.Date; importjava.util.List; publicclassConverVideo{ privateDatedt; privatelongbegintime; privateStringPATH; privateStringfilerealname;//文件名不包括扩展名 privateStringfilename;//包括扩展名 privateStringvideofolder="other/";//别的格式视频的目录 privateStringflvfolder="flv/";//flv视频的目录 privateStringffmpegpath="ffmpeg/ffmpeg.exe";//ffmpeg.exe的目录 privateStringmencoderpath="ffmpeg/mencoder";//mencoder的目录 privateStringvideoRealPath="flv/";//截图的视频目录; privateStringimageRealPath="img/";//截图的存放目录 //privateStringbatrealpath="ffmpeg/ffmpeg.bat";//bat目录 publicConverVideo(){} publicConverVideo(Stringpath){ PATH=path; } publicStringgetPATH(){ returnPATH; } publicvoidsetPATH(Stringpath){ PATH=path; } publicbooleanbeginConver(){ Filefi=newFile(PATH); filename=fi.getName(); filerealname=filename.substring(0,filename.lastIndexOf(".")) .toLowerCase(); Conver.OutShowLog.append("----接收到文件("+PATH+")需要转换--------------------------"); if(!checkfile(PATH)){ Conver.OutShowLog.append(PATH+"文件不存在"+""); returnfalse; } dt=newDate(); begintime=dt.getTime(); Conver.OutShowLog.append("----开始转文件("+PATH+")--------------------------"); if(process()){ Datedt2=newDate(); Conver.OutShowLog.append("转换成功"); longendtime=dt2.getTime(); longtimecha=(endtime-begintime); Stringtotaltime=sumTime(timecha); Conver.OutShowLog.append("共用了:"+totaltime+""); if(processImg()){ Conver.OutShowLog.append("截图成功了"); }else{ Conver.OutShowLog.append("截图不成功了"); } PATH=null; returntrue; }else{ PATH=null; returnfalse; } } publicbooleanprocessImg(){ //System.out.println(newfilename+"->"+newimg); Listcommend=newjava.util.ArrayList(); commend.add(ffmpegpath); commend.add("-i"); commend.add(videoRealPath+filerealname+".flv"); commend.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{ ProcessBuilderbuilder=newProcessBuilder(); builder.command(commend); builder.start(); returntrue; }catch(Exceptione){ e.printStackTrace(); returnfalse; } } privatebooleanprocess(){ inttype=checkContentType(); booleanstatus=false; if(type==0){ //status=processFLV(PATH);//直接将文件转为flv文件 status=processFLV(PATH); }elseif(type==1){ Stringavifilepath=processAVI(type); if(avifilepath==null) returnfalse; //avi文件没有得到 else{ System.out.println("kaishizhuang"); status=processFLV(avifilepath);//将avi转为flv } } returnstatus; } privateintcheckContentType(){ Stringtype=PATH.substring(PATH.lastIndexOf(".")+1,PATH.length()) .toLowerCase(); //ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) if(type.equals("avi")){ return0; }elseif(type.equals("mpg")){ return0; }elseif(type.equals("wmv")){ return0; }elseif(type.equals("3gp")){ return0; }elseif(type.equals("mov")){ return0; }elseif(type.equals("mp4")){ return0; }elseif(type.equals("asf")){ return0; }elseif(type.equals("asx")){ return0; }elseif(type.equals("flv")){ return0; } //对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), //可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式. elseif(type.equals("wmv9")){ return1; }elseif(type.equals("rm")){ return1; }elseif(type.equals("rmvb")){ return1; } return9; } privatebooleancheckfile(Stringpath){ Filefile=newFile(path); if(!file.isFile()){ returnfalse; }else{ returntrue; } } //对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式. privateStringprocessAVI(inttype){ Listcommend=newjava.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"); //命令类型:mencoder1.rmvb-oacmp3lame-lameoptspreset=64-ovcxvid //-xvidencoptsbitrate=600-ofavi-ormvb.avi try{ ProcessBuilderbuilder=newProcessBuilder(); builder.command(commend); Processp=builder.start(); doWaitFor(p); returnvideofolder+filerealname+".avi"; }catch(Exceptione){ e.printStackTrace(); returnnull; } } //ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) privatebooleanprocessFLV(Stringoldfilepath){ if(!checkfile(PATH)){ System.out.println(oldfilepath+"isnotfile"); returnfalse; } Listcommend=newjava.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"); commend.add("-r"); commend.add("24"); commend.add("-y"); commend.add(flvfolder+filerealname+".flv"); try{ ProcessBuilderbuilder=newProcessBuilder(); Stringcmd=commend.toString(); builder.command(commend); //builder.redirectErrorStream(true); Processp=builder.start(); doWaitFor(p); p.destroy(); deleteFile(oldfilepath); returntrue; }catch(Exceptione){ e.printStackTrace(); returnfalse; } } publicintdoWaitFor(Processp) { InputStreamin=null; InputStreamerr=null; intexitValue=-1;//returnedtocallerwhenpisfinished try{ System.out.println("comeing"); in=p.getInputStream(); err=p.getErrorStream(); booleanfinished=false;//Settotruewhenpisfinished while(!finished){ try{ while(in.available()>0){ //Printtheoutputofoursystemcall Characterc=newCharacter((char)in.read()); System.out.print(c); } while(err.available()>0){ //Printtheoutputofoursystemcall Characterc=newCharacter((char)err.read()); System.out.print(c); } //AsktheprocessforitsexitValue.Iftheprocess //isnotfinished,anIllegalThreadStateException //isthrown.Ifitisfinished,wefallthroughand //thevariablefinishedissettotrue. exitValue=p.exitValue(); finished=true; }catch(IllegalThreadStateExceptione){ //Processisnotfinishedyet; //SleepalittletosaveonCPUcycles Thread.currentThread().sleep(500); } } }catch(Exceptione){ //unexpectedexception!printitoutfordebugging... System.err.println("doWaitFor();:unexpectedexception-" +e.getMessage()); }finally{ try{ if(in!=null) { in.close(); } }catch(IOExceptione){ System.out.println(e.getMessage()); } if(err!=null) { try{ err.close(); }catch(IOExceptione){ System.out.println(e.getMessage()); } } } //returncompletionstatustocaller returnexitValue; } publicvoiddeleteFile(Stringfilepath){ Filefile=newFile(filepath); if(PATH.equals(filepath)){ if(file.delete()){ System.out.println("文件"+filepath+"已删除"); } }else{ if(file.delete()){ System.out.println("文件"+filepath+"已删除"); } Filefiledelete2=newFile(PATH); if(filedelete2.delete()){ System.out.println("文件"+PATH+"已删除"); } } } publicStringsumTime(longms){ intss=1000; longmi=ss*60; longhh=mi*60; longdd=hh*24; longday=ms/dd; longhour=(ms-day*dd)/hh; longminute=(ms-day*dd-hour*hh)/mi; longsecond=(ms-day*dd-hour*hh-minute*mi)/ss; longmilliSecond=ms-day*dd-hour*hh-minute*mi-second *ss; StringstrDay=day<10?"0"+day+"天":""+day+"天"; StringstrHour=hour<10?"0"+hour+"小时":""+hour+"小时"; StringstrMinute=minute<10?"0"+minute+"分":""+minute+"分"; StringstrSecond=second<10?"0"+second+"秒":""+second+"秒"; StringstrMilliSecond=milliSecond<10?"0"+milliSecond:"" +milliSecond; strMilliSecond=milliSecond<100?"0"+strMilliSecond+"毫秒":"" +strMilliSecond+"毫秒"; returnstrDay+""+strHour+":"+strMinute+":"+strSecond+"" +strMilliSecond; } }如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!