天天看點

JAVA+ffmpeg+mencoder轉換視訊

近來需要做一個線上浏覽視訊的功能,剛開始考慮的思路是:将視訊上傳之後,在頁面上根據不同的視訊格式嵌入不同的播放代碼,可是這樣的話頁面上的代碼量會非常的多,而且有的視訊格式還得使用不同的播放器來播放,這樣覺得很麻煩,實用性不強。後來查詢得知:可以将各種視訊格式轉為flv的格式,然後在頁面上隻需要有一個flash播放器即可播放flv檔案了,這樣的話就不用考慮使用不同的播放器來播放的情況,而且頁面代碼簡潔。以下為轉換代碼:

(1)将視訊轉換過程做成一個幫助類:

import java.io.BufferedReader;  
import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.util.List;  
public class ConvertSingleVideo {
	
	private static String mencoder_home = "D:\\javaserve\\mencoder\\mencoder.exe";//mencoder.exe所放的路徑
	private static String ffmpeg_home = "D:\\javaserve\\ffmpeg\\ffmpeg.exe";//ffmpeg.exe所放的路徑
	
	public static String inputFile_home = "F:\\java\\work\\jingpinkecheng\\WebRoot\\upload\\input\\";//需轉換的檔案的位置
	public static String outputFile_home = "D:\\javaserve\\tomcat\\apache-tomcat-7.0.32\\webapps\\jingpinkecheng\\upload\\output\\";//轉換後的flv檔案所放的檔案夾位置
	private String tempFile_home;//存放rm,rmvb等無法使用ffmpeg直接轉換為flv檔案先轉成的avi檔案
	 
	 public ConvertSingleVideo(String tempFilePath){
		 this.tempFile_home = tempFilePath;
	 }
	 
	    /** 
	     *  功能函數 
	     * @param inputFile 待處理視訊,需帶路徑 
	     * @param outputFile 處理後視訊,需帶路徑 
	     * @return 
	     */  
	    public  boolean convert(String inputFile, String outputFile)  
	    {  
	        if (!checkfile(inputFile)) {  
	            System.out.println(inputFile + " is not file");  
	            return false;  
	        }  
	        if (process(inputFile,outputFile)) {  
	            System.out.println("ok");  
	            return true;  
	        }  
	        return false;  
	    }  
	    //檢查檔案是否存在  
	    private  boolean checkfile(String path) {  
	        File file = new File(path);  
	        if (!file.isFile()) {  
	            return false;  
	        }  
	        return true;  
	    }  
	    /** 
	     * 轉換過程 :先檢查檔案類型,在決定調用 processFlv還是processAVI 
	     * @param inputFile 
	     * @param outputFile 
	     * @return 
	     */  
	    private  boolean process(String inputFile,String outputFile) {  
	        int type = checkContentType( inputFile);  
	        boolean status = false;  
	        if (type == 0) {  
	            status = processFLV(inputFile,outputFile);// 直接将檔案轉為flv檔案  
	        } else if (type == 1) {  
	            String avifilepath = processAVI(type,inputFile);  
	            if (avifilepath == null)  
	                return false;// avi檔案沒有得到  
	            status = processFLV(avifilepath,outputFile);// 将avi轉為flv  
	        }  
	        return status;  
	    }  
	    /** 
	     * 檢查視訊類型 
	     * @param inputFile 
	     * @return ffmpeg 能解析傳回0,不能解析傳回1 
	     */  
	    private  int checkContentType(String inputFile) {  
	        String type = inputFile.substring(inputFile.lastIndexOf(".") + 1,inputFile.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;  
	    }  
	    /** 
	     *  ffmepg: 能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 
	     * @param inputFile 
	     * @param outputFile 
	     * @return 
	     */  
	    private  boolean processFLV(String inputFile,String outputFile) {  
	        if (!checkfile(inputFile)) {  
	            System.out.println(inputFile + " is not file");  
	            return false;  
	        } 
	        File file = new File(outputFile);
	        if(file.exists()){
	        	System.out.println("flv檔案已經存在!無需轉換");
	        	return true;
	        } else {
	        	System.out.println("正在轉換成flv檔案……");
	        	
	        	List<String> commend = new java.util.ArrayList<String>();  
	 	        //低精度  
	 	        commend.add(ffmpeg_home);
	 	        commend.add("-i");  
	 	        commend.add(inputFile);  
	 	        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"); 
	 	        // 清晰度 -qscale 4 為最好但檔案大, -qscale 6就可以了
	 	        commend.add("-qscale");  
	 	        commend.add("4");  
	 	        commend.add("-y");  
	 	        commend.add(outputFile);  
	 	        StringBuffer test=new StringBuffer();  
	 	        for(int i=0;i<commend.size();i++)  
	 	            test.append(commend.get(i)+" ");  
	 	        System.out.println(test);  
	 	        try {  
	 	            ProcessBuilder builder = new ProcessBuilder();  
	 	            builder.command(commend);  
	 	            builder.start(); 
	 	            return true;  
	 	        } catch (Exception e) {  
	 	            e.printStackTrace();  
	 	            return false;  
	 	        }  
	 	       
	        }
	       
	    }  
	    /** 
	     * Mencoder: 
	     * 對ffmpeg無法解析的檔案格式(wmv9,rm,rmvb等),可以先用别的工具(mencoder)轉換為avi(ffmpeg能解析的)格式. 
	     * @param type 
	     * @param inputFile 
	     * @return 
	     */  
	    private  String processAVI(int type,String inputFile) {  
	        File file =new File(tempFile_home);  
	        if(file.exists()){
	        	System.out.println("avi檔案已經存在!無需轉換");
	        	return tempFile_home;
	        }  
	        List<String> commend = new java.util.ArrayList<String>();  
	        commend.add(mencoder_home);  
	        commend.add(inputFile);  
	        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(tempFile_home);  
	        StringBuffer test=new StringBuffer();  
	        for(int i=0;i<commend.size();i++)  
	            test.append(commend.get(i)+" ");  
	        System.out.println(test);  
	        try   
	        {  
	            ProcessBuilder builder = new ProcessBuilder();  
	            builder.command(commend);  
	            Process p=builder.start();  
	            /** 
	             * 清空Mencoder程序 的輸出流和錯誤流 
	             * 因為有些本機平台僅針對标準輸入和輸出流提供有限的緩沖區大小, 
	             * 如果讀寫子程序的輸出流或輸入流迅速出現失敗,則可能導緻子程序阻塞,甚至産生死鎖。  
	             */  
	            final InputStream is1 = p.getInputStream();  
	            final InputStream is2 = p.getErrorStream();  
	            new Thread() {  
	                public void run() {  
	                    BufferedReader br = new BufferedReader(new InputStreamReader(is1));  
	                    try {  
	                        String lineB = null;  
	                        while ((lineB = br.readLine()) != null ){  
	                            if(lineB != null)System.out.println(lineB);  
	                        }  
	                    } catch (IOException e) {  
	                        e.printStackTrace();  
	                    }  
	                }  
	            }.start();   
	            new Thread() {  
	                public void run() {  
	                    BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));  
	                    try {  
	                        String lineC = null;  
	                        while ( (lineC = br2.readLine()) != null){  
	                            if(lineC != null)System.out.println(lineC);  
	                        }  
	                    } catch (IOException e) {  
	                        e.printStackTrace();  
	                    }  
	                }  
	            }.start();   
	              
	            //等Mencoder程序轉換結束,再調用ffmpeg程序  
	            p.waitFor();  
	             System.out.println("who cares");  
	            return tempFile_home;  
	        }catch (Exception e){   
	            System.err.println(e);   
	            return null;  
	        }   
	    }  
	}  
           

(2)action中調用該類的方法:

public String showResourceJiaoxueshipin() throws IOException{
		resourcejiaoxueshipin = itemService.findById(resourcejiaoxueshipinid);
		
		String fileName = resourcejiaoxueshipin.getFirst_img();
		ConvertSingleVideo conver = new ConvertSingleVideo("F:\\java\\work\\jingpinkecheng\\WebRoot\\upload\\temp\\" + fileName.substring(0,fileName.lastIndexOf("."))+".avi");
		
		conver.convert(ConvertSingleVideo.inputFile_home + fileName, ConvertSingleVideo.outputFile_home + fileName.substring(0,fileName.lastIndexOf("."))+".flv");
		
		HttpSession session = request.getSession();
		fileName = new String(fileName.getBytes("UTF-8"),"GBK");//存到session後在jsp頁面取出的值是GBK("亂碼"),是以這裡先變成亂碼,傳輸過去之後即可消除
		session.setAttribute("jiaoxueshipinName",fileName.substring(0,fileName.lastIndexOf("."))+".flv" );
		System.out.println("我是測試:"+session.getAttribute("jiaoxueshipinName"));
		 return "success";
		
		
		
	}
           

(3)jsp代碼:

隻需要在頁面嵌入一個flash播放器,我這裡使用vcastr22.swf,并且将flv檔案的路徑填寫正确即可。嵌入代碼如下:

<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">
		<param name="movie" value="../upload/vcastr22.swf?vcastr_file=../upload/output/${sessionScope.jiaoxueshipinName }">
		<param name="quality" value="high">
		<param name="allowFullScreen" value="true" />
		<!-- src裡就是播放器的路徑以及需要顯示的flv檔案的路徑,路徑一定要正确! -->
		<embed
			src="../upload/vcastr22.swf?vcastr_file=../upload/output/${sessionScope.jiaoxueshipinName }"
			quality="high"
			pluginspage="http://www.macromedia.com/go/getflashplayer"
			type="application/x-shockwave-flash" width="500" height="350">
		</embed>
	</object> 
           

經過以上步驟,即可成功的完成視訊的轉換即線上浏覽。浏覽效果如下:

JAVA+ffmpeg+mencoder轉換視訊

參考資料:

http://blog.csdn.net/jason20075563/article/details/6066563