打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JAVA+ffmpeg+mencoder转换视频

FFmpeg是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用LGPL或GPL许可证(依据你选择的组件)。它提供了录制、转换以及流化音视频的完整解决方案。它包含了非常先进的音频/视频编解码库libavcodec,为了保证高可移植性和编解码质量,libavcodec里很多codec都是从头开发的。FFmpeg在Linux平台下开发,但它同样也可以在其它操作系统环境中编译运行。

mencoder 是一款命令行方式的视频处理软件,是Mplayer自带的编码工具(Mplayer是Linux下的播放器,开源,支持几乎所有视频格式的播放,现在有windows和Mac版本)。

这种方式来实现在web页面播放视频的思路如下:可以将各种视频格式转为flv的格式,然后在页面上只需要有一个flash播放器即可播放flv文件了,这样的话就不用考虑使用不同的播放器来播放的情况,而且页面代码简洁。

以下为转换代码:

(1)将视频转换过程做成一个帮助类:

  1. import java.io.BufferedReader;    
  2. import java.io.File;    
  3. import java.io.IOException;    
  4. import java.io.InputStream;    
  5. import java.io.InputStreamReader;    
  6. import java.util.List;    
  7. public class ConvertSingleVideo {  
  8.       
  9.     private static String mencoder_home = "D:\\javaserve\\mencoder\\mencoder.exe";//mencoder.exe所放的路径  
  10.     private static String ffmpeg_home = "D:\\javaserve\\ffmpeg\\ffmpeg.exe";//ffmpeg.exe所放的路径  
  11.       
  12.     public static String inputFile_home = "F:\\java\\work\\jingpinkecheng\\WebRoot\\upload\\input\\";//需转换的文件的位置  
  13.     public static String outputFile_home = "D:\\javaserve\\tomcat\\apache-tomcat-7.0.32\\webapps\\jingpinkecheng\\upload\\output\\";//转换后的flv文件所放的文件夹位置  
  14.     private String tempFile_home;//存放rm,rmvb等无法使用ffmpeg直接转换为flv文件先转成的avi文件  
  15.        
  16.      public ConvertSingleVideo(String tempFilePath){  
  17.          this.tempFile_home = tempFilePath;  
  18.      }  
  19.        
  20.         /**  
  21.          *  功能函数  
  22.          * @param inputFile 待处理视频,需带路径  
  23.          * @param outputFile 处理后视频,需带路径  
  24.          * @return  
  25.          */    
  26.         public  boolean convert(String inputFile, String outputFile)    
  27.         {    
  28.             if (!checkfile(inputFile)) {    
  29.                 System.out.println(inputFile + " is not file");    
  30.                 return false;    
  31.             }    
  32.             if (process(inputFile,outputFile)) {    
  33.                 System.out.println("ok");    
  34.                 return true;    
  35.             }    
  36.             return false;    
  37.         }    
  38.         //检查文件是否存在    
  39.         private  boolean checkfile(String path) {    
  40.             File file = new File(path);    
  41.             if (!file.isFile()) {    
  42.                 return false;    
  43.             }    
  44.             return true;    
  45.         }    
  46.         /**  
  47.          * 转换过程 :先检查文件类型,在决定调用 processFlv还是processAVI  
  48.          * @param inputFile  
  49.          * @param outputFile  
  50.          * @return  
  51.          */    
  52.         private  boolean process(String inputFile,String outputFile) {    
  53.             int type = checkContentType( inputFile);    
  54.             boolean status = false;    
  55.             if (type == 0) {    
  56.                 status = processFLV(inputFile,outputFile);// 直接将文件转为flv文件    
  57.             } else if (type == 1) {    
  58.                 String avifilepath = processAVI(type,inputFile);    
  59.                 if (avifilepath == null)    
  60.                     return false;// avi文件没有得到    
  61.                 status = processFLV(avifilepath,outputFile);// 将avi转为flv    
  62.             }    
  63.             return status;    
  64.         }    
  65.         /**  
  66.          * 检查视频类型  
  67.          * @param inputFile  
  68.          * @return ffmpeg 能解析返回0,不能解析返回1  
  69.          */    
  70.         private  int checkContentType(String inputFile) {    
  71.             String type = inputFile.substring(inputFile.lastIndexOf(".") + 1,inputFile.length()).toLowerCase();    
  72.             // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)    
  73.             if (type.equals("avi")) {    
  74.                 return 0;    
  75.             } else if (type.equals("mpg")) {    
  76.                 return 0;    
  77.             } else if (type.equals("wmv")) {    
  78.                 return 0;    
  79.             } else if (type.equals("3gp")) {    
  80.                 return 0;    
  81.             } else if (type.equals("mov")) {    
  82.                 return 0;    
  83.             } else if (type.equals("mp4")) {    
  84.                 return 0;    
  85.             } else if (type.equals("asf")) {    
  86.                 return 0;    
  87.             } else if (type.equals("asx")) {    
  88.                 return 0;    
  89.             } else if (type.equals("flv")) {    
  90.                 return 0;    
  91.             }    
  92.             // 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),    
  93.             // 可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.    
  94.             else if (type.equals("wmv9")) {    
  95.                 return 1;    
  96.             } else if (type.equals("rm")) {    
  97.                 return 1;    
  98.             } else if (type.equals("rmvb")) {    
  99.                 return 1;    
  100.             }    
  101.             return 9;    
  102.         }    
  103.         /**  
  104.          *  ffmepg: 能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)  
  105.          * @param inputFile  
  106.          * @param outputFile  
  107.          * @return  
  108.          */    
  109.         private  boolean processFLV(String inputFile,String outputFile) {    
  110.             if (!checkfile(inputFile)) {    
  111.                 System.out.println(inputFile + " is not file");    
  112.                 return false;    
  113.             }   
  114.             File file = new File(outputFile);  
  115.             if(file.exists()){  
  116.                 System.out.println("flv文件已经存在!无需转换");  
  117.                 return true;  
  118.             } else {  
  119.                 System.out.println("正在转换成flv文件……");  
  120.                   
  121.                 List<String> commend = new java.util.ArrayList<String>();    
  122.                 //低精度    
  123.                 commend.add(ffmpeg_home);  
  124.                 commend.add("-i");    
  125.                 commend.add(inputFile);    
  126.                 commend.add("-ab");    
  127.                 commend.add("128");    
  128.                 commend.add("-acodec");    
  129.                 commend.add("libmp3lame");    
  130.                 commend.add("-ac");    
  131.                 commend.add("1");    
  132.                 commend.add("-ar");    
  133.                 commend.add("22050");    
  134.                 commend.add("-r");    
  135.                 commend.add("29.97");   
  136.                 // 清晰度 -qscale 4 为最好但文件大, -qscale 6就可以了  
  137.                 commend.add("-qscale");    
  138.                 commend.add("4");    
  139.                 commend.add("-y");    
  140.                 commend.add(outputFile);    
  141.                 StringBuffer test=new StringBuffer();    
  142.                 for(int i=0;i<commend.size();i++)    
  143.                     test.append(commend.get(i)+" ");    
  144.                 System.out.println(test);    
  145.                 try {    
  146.                     ProcessBuilder builder = new ProcessBuilder();    
  147.                     builder.command(commend);    
  148.                     builder.start();   
  149.                     return true;    
  150.                 } catch (Exception e) {    
  151.                     e.printStackTrace();    
  152.                     return false;    
  153.                 }    
  154.                  
  155.             }  
  156.              
  157.         }    
  158.         /**  
  159.          * Mencoder:  
  160.          * 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)转换为avi(ffmpeg能解析的)格式.  
  161.          * @param type  
  162.          * @param inputFile  
  163.          * @return  
  164.          */    
  165.         private  String processAVI(int type,String inputFile) {    
  166.             File file =new File(tempFile_home);    
  167.             if(file.exists()){  
  168.                 System.out.println("avi文件已经存在!无需转换");  
  169.                 return tempFile_home;  
  170.             }    
  171.             List<String> commend = new java.util.ArrayList<String>();    
  172.             commend.add(mencoder_home);    
  173.             commend.add(inputFile);    
  174.             commend.add("-oac");    
  175.             commend.add("mp3lame");    
  176.             commend.add("-lameopts");    
  177.             commend.add("preset=64");    
  178.             commend.add("-ovc");    
  179.             commend.add("xvid");    
  180.             commend.add("-xvidencopts");    
  181.             commend.add("bitrate=600");    
  182.             commend.add("-of");    
  183.             commend.add("avi");    
  184.             commend.add("-o");    
  185.             commend.add(tempFile_home);    
  186.             StringBuffer test=new StringBuffer();    
  187.             for(int i=0;i<commend.size();i++)    
  188.                 test.append(commend.get(i)+" ");    
  189.             System.out.println(test);    
  190.             try     
  191.             {    
  192.                 ProcessBuilder builder = new ProcessBuilder();    
  193.                 builder.command(commend);    
  194.                 Process p=builder.start();    
  195.                 /**  
  196.                  * 清空Mencoder进程 的输出流和错误流  
  197.                  * 因为有些本机平台仅针对标准输入和输出流提供有限的缓冲区大小,  
  198.                  * 如果读写子进程的输出流或输入流迅速出现失败,则可能导致子进程阻塞,甚至产生死锁。   
  199.                  */    
  200.                 final InputStream is1 = p.getInputStream();    
  201.                 final InputStream is2 = p.getErrorStream();    
  202.                 new Thread() {    
  203.                     public void run() {    
  204.                         BufferedReader br = new BufferedReader(new InputStreamReader(is1));    
  205.                         try {    
  206.                             String lineB = null;    
  207.                             while ((lineB = br.readLine()) != null ){    
  208.                                 if(lineB != null)System.out.println(lineB);    
  209.                             }    
  210.                         } catch (IOException e) {    
  211.                             e.printStackTrace();    
  212.                         }    
  213.                     }    
  214.                 }.start();     
  215.                 new Thread() {    
  216.                     public void run() {    
  217.                         BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));    
  218.                         try {    
  219.                             String lineC = null;    
  220.                             while ( (lineC = br2.readLine()) != null){    
  221.                                 if(lineC != null)System.out.println(lineC);    
  222.                             }    
  223.                         } catch (IOException e) {    
  224.                             e.printStackTrace();    
  225.                         }    
  226.                     }    
  227.                 }.start();     
  228.                     
  229.                 //等Mencoder进程转换结束,再调用ffmpeg进程    
  230.                 p.waitFor();    
  231.                  System.out.println("who cares");    
  232.                 return tempFile_home;    
  233.             }catch (Exception e){     
  234.                 System.err.println(e);     
  235.                 return null;    
  236.             }     
  237.         }    
  238.     }    

(2)action中调用该类的方法:

  1. public String showResourceJiaoxueshipin() throws IOException{  
  2.         resourcejiaoxueshipin = itemService.findById(resourcejiaoxueshipinid);  
  3.           
  4.         String fileName = resourcejiaoxueshipin.getFirst_img();  
  5.         ConvertSingleVideo conver = new ConvertSingleVideo("F:\\java\\work\\jingpinkecheng\\WebRoot\\upload\\temp\\" + fileName.substring(0,fileName.lastIndexOf("."))+".avi");  
  6.           
  7.         conver.convert(ConvertSingleVideo.inputFile_home + fileName, ConvertSingleVideo.outputFile_home + fileName.substring(0,fileName.lastIndexOf("."))+".flv");  
  8.           
  9.         HttpSession session = request.getSession();  
  10.         fileName = new String(fileName.getBytes("UTF-8"),"GBK");//存到session后在jsp页面取出的值是GBK("乱码"),所以这里先变成乱码,传输过去之后即可消除  
  11.         session.setAttribute("jiaoxueshipinName",fileName.substring(0,fileName.lastIndexOf("."))+".flv" );  
  12.         System.out.println("我是测试:"+session.getAttribute("jiaoxueshipinName"));  
  13.          return "success";  
  14.           
  15.           
  16.           
  17.     }  

3)jsp代码:

只需要在页面嵌入一个flash播放器,我这里使用vcastr22.swf,并且将flv文件的路径填写正确即可。嵌入代码如下:

  1. <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" height="120" width="190">  
  2.     <param name="movie" value="../upload/vcastr22.swf?vcastr_file=../upload/output/${sessionScope.jiaoxueshipinName }">  
  3.     <param name="quality" value="high">  
  4.     <param name="allowFullScreen" value="true" />  
  5.     <!-- src里就是播放器的路径以及需要显示的flv文件的路径,路径一定要正确! -->  
  6.     <embed  
  7.         src="../upload/vcastr22.swf?vcastr_file=../upload/output/${sessionScope.jiaoxueshipinName }"  
  8.         quality="high"  
  9.         pluginspage="http://www.macromedia.com/go/getflashplayer"  
  10.         type="application/x-shockwave-flash" width="500" height="350">  
  11.     </embed>  
  12. </object>   


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java实现视频上传和播放SpringMVC + Mybatis + ckplayer+ffmpeg+mencoder
ffmpeg.exe与mencoder.exe实例转换操作
web/java实现多种格式视频上传、转码、截图、播放、下载等功能附源码(详细)
FFmpeg:视频转码、剪切、合并、播放速调整
Java+Windows+ffmpeg实现视频转换
java实现视频文件转换为flv(带文件缩略图)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服