java实现视频的转码

package com.bayside.crawler.collect.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;  
import java.util.Calendar;  
import java.util.List;

import com.bayside.crawler.collect.constant.VideoConstant;  
  

public class ConvertVideo {
     private final static String PATH = "D:\\tempvideo\\20181207.flv";  
     public static void main(String[] args) {
//    	String fileName = PATH.split("\\")[PATH.split("\\").length-1].split("\\.")[0];
     	String fileName = PATH.split("\\.")[0];
     	List<String> list = new ArrayList<>();
     	list.add(PATH);
     	list.add("D:\\tempvideo\\fOl5dJ1w44JusEKDsazjg_1543248000000_山东公共频道_身体健康.gvfy.ts");                                        
//     	for(String str: list){
//     		transcod(PATH);
//     	}
 		transcod(PATH);

	}
    /**
     * 视频转码
     * @param path  视频的链接
     */
    public static void transcod(String path) {  
    	String fileName = VideoConstant.tofileTemp + path.split("\\\\")[path.split("\\\\").length-1];
    	fileName = fileName.substring(0, fileName.lastIndexOf("."));
    	System.out.println(fileName.split("\\\\")[fileName.split("\\\\").length-1]);
        if (!checkfile(path)) {   //判断路径是不是一个文件
            System.out.println(path + " is not file");  
            return;  
        }  
        if (process(path, fileName)) {        //执行转码任务
            System.out.println("ok");  
            if(FileManager.copyFile(fileName + ".mp4", VideoConstant.tofile + fileName.split("\\\\")[fileName.split("\\\\").length-1] + ".mp4")){
	        	if(FileManager.deleteFile(fileName + ".mp4")){
	        		System.out.println("复制成功,删除成功");
	        		
	        	}
	        }
        }
    }  
  
    private static boolean checkfile(String path) {  
        File file = new File(path);  
        if (!file.isFile()) {  
            return false;  
        }  
        return true;  
    }  
    
    private static boolean process(String path, String fileName) { 
        // 判断视频的类型
        int type = checkContentType(path);  
        boolean status = false;  
        //如果是ffmpeg可以转换的类型直接转码,否则先用mencoder转码成AVI
        if (type == 0) {  
            System.out.println("直接将文件转为mp4文件");  
            String type2 = path.substring(path.lastIndexOf(".") + 1, path.length());
            if(type2.equals("wmv")){
            	FileManager.copyFile(path, fileName + ".mp4");
            	status = true;
            }else {
            	long startTime=System.currentTimeMillis();//记录开始时间
            	 status = processMP4(path, fileName);// 直接将文件转为flv文件  
            	 long endTime=System.currentTimeMillis();//记录结束时间
     			float excTime=(float)(endTime-startTime)/1000;
     			System.out.println("执行时间:"+excTime+"s");
     			FileManager.writeToFile(VideoConstant.timeout, true, "执行时间:"+excTime+"s");
			}
            if(FileManager.DeleteFolder(path)){
            	System.out.println(path + "删除成功");
            }
        } else if (type == 1) {  
            String avifilepath = processAVI(path, type, fileName);
            if(FileManager.DeleteFolder(path)){
            	System.out.println(path + "删除成功");
            }
            if (avifilepath == null)  
                return false;// avi文件没有得到  
            status = processMP4( avifilepath, fileName);// 将avi转为flv 
            if (FileManager.DeleteFolder(avifilepath)) {
				System.out.println(avifilepath + "删除成功");
			}
        }  
        return status;  
    }  
  
    private static int checkContentType(String path) {  
        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;  
        }  else if (type.equals("ts")) {
			return 0;
		}else if (type.equals("f4v")) {
			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能解析的)格式.  
    private static String processAVI(String path, int type, String FileName) {  
        List<String> commend = new ArrayList<String>();  
        commend.add(VideoConstant.mencoder);  
        commend.add(path);  
//        commend.add("-oac");  
//        commend.add("lavc");  
//        commend.add("-lavcopts");  
//        commend.add("acodec=mp3:abitrate=64");  
//        commend.add("-ovc");  
//        commend.add("xvid");  
//        commend.add("-xvidencopts");  
//        commend.add("bitrate=1080");  
//        commend.add("-of");  
//        commend.add("avi");  
//        commend.add("-o"); 

        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(FileName + ".avi");  
        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();  
  
            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);  
                            }
                        }  
                        br.close();
                    } 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);  
                            }
                        }  
                        br2.close();
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }.start();  
  
            // 等Mencoder进程转换结束,再调用ffmepg进程  
            p.waitFor();  
            System.out.println("who cares");  
            return FileName + ".avi";  
        } catch (Exception e) {  
            System.err.println(e);  
            return null;  
        } 

        
//        try {  
//            //调用线程命令启动转码
//            ProcessBuilder builder = new ProcessBuilder();  
//            builder.command(commend);  
//            builder.start();  
//            Thread.sleep(1000);
//            return FileName + ".avi";  
//        } catch (Exception e) {  
//            e.printStackTrace();  
//            return null;  
//        }
    }  
  
    // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)  
    private static boolean processMP4(String oldfilepath, String fileName) {  
  
        if (!checkfile(oldfilepath)) {  
            System.out.println(oldfilepath + " is not file");  
            return false;  
        }  
          
        // 文件命名  
        Calendar c = Calendar.getInstance();  
        String savename = String.valueOf(c.getTimeInMillis())+ Math.round(Math.random() * 100000);  
        List<String> commend = new ArrayList<String>();  
        String type = oldfilepath.split("\\.")[1];  //D:\tempvideo\nnews2018120601.wmv
    	commend.add(VideoConstant.ffmpeg);
        commend.add("-y");
        commend.add("-i");
        commend.add(oldfilepath);
        commend.add("-c:v");
        commend.add("libx264");
        commend.add("-c:a");
        commend.add("copy");
        commend.add("-bsf:a");
        commend.add("aac_adtstoasc");
        commend.add("-vf");
        commend.add("mpdecimate,setpts=N/FRAME_RATE/TB");
        commend.add("-f");
        commend.add("mp4");
        commend.add(fileName + ".mp4");
        StringBuffer test = new StringBuffer();  
        for (int i = 0; i < commend.size(); i++) {  
            test.append(commend.get(i) + " ");  
        }  
  
        try {  
        	Process videoProcess = new ProcessBuilder(commend).redirectErrorStream(true).start();
            
        	new PrintStream(videoProcess.getInputStream()).start();
        	            
        	videoProcess.waitFor();
        	            
        	return true;
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  finally {
			
		}
    }  
}
class PrintStream extends Thread 
{
    java.io.InputStream __is = null;
    public PrintStream(java.io.InputStream is) 
    {
        __is = is;
    } 

    public void run() 
    {
        try 
        {
            while(this != null) 
            {
                int _ch = __is.read();
                if(_ch != -1) 
                    System.out.print((char)_ch); 
                else break;
               
            }
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        } 
//        finally {
//			try {
//				if(__is != null){
//					__is.close();
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
    }
}
发布了28 篇原创文章 · 获赞 16 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览