ffmpeg视频格式转换for windows and linux

背景:

       项目架构:B/S

       开发语言:Java

       项目需要将dav格式的视频转换为mp4格式,实现在线观看,先进行安装步骤的描述,代码后面贴进来

一、windows

      1.ffmpeg for windows官方下载即可

      2.笔者下载的是解压版的,无需安装,解压后配置环境变量path(例:D:\ffmpeg-win64\bin),这个目录下有三个可执行文件 ffmpeg.exe、ffplay.exe、ffprobe.exe,我们需要用的是是 ffmpeg.exe,在后面的代码中会用到,使用的方式是Java调用dos命令,其实此处也可以不用配置环境变量,但是不推荐这么做,因为这样就把代码写死了,就是在dos命令中写上ffmpeg的具体路径,在后面的代码中我会进行标注。

       将dav格式视频转为mp4我采用如下命令(linux下也是如此):

                           ffmpeg  -i  456.dav  -c:v  libx264  -strict  -2  123.mp4

      windows下面就是这样简单,结束了!

二、linux for ubuntu

           1.下载ffmpeg 和 x264,我是官方下载的,速度及其慢,文件如下:

            ffmpeg-3.2.tar.bz2、last_x264.tar.bz2

           2.编译安装 安装x264 

          到解压的目录下执行下列命令

      ./configure --prefix=/usr/local/x264 --enable-shared --enable-static --enable-yasm 
      make    
      make install

             /usr/local/x264 为 x264的安装目录

         2.编译安装 安装ffmpeg

      (1) 到解压的目录下执行下列命令

     configure --prefix=/usr/local/ffmpeg --enable-shared --enable-yasm --enable-libx264 --enable-gpl --enable-pthreads --extra-cflags=-I/usr/local/x264/include --extra-ldflags=-L/usr/local/x264/lib

      make    
      make install

       (3) 配置环境变量:vim /etc/profile

        在文件最后添加 :

     

    export FFMPEG_HOME=/usr/local/ffmpeg #这个目录是configure 中配置过的
    export PATH=$FFMPEG_HOME/bin:$PATH

        

       (4)使修改立即生效
         source /etc/profile
        执行  ffmpeg -version 可查看ffmpeg版本

       3.安装完后进行转码测试

        root@iZ23lgb0dxdZ:/# ffmpeg -i  16.51.13-16.51.13[A][0@0][0].dav -c:v libx264 -strict -2 123.mp4
        错误:ffmpeg: error while loading shared libraries: libx264.so.148: cannot open shared object file: No such file or directory

        未找到 libx264.so.148,这时进行第4步,如果没有报错,下面就不用看了

         4.使用 ldd `which ffmpeg`  查看缺少的库

         使用find -name libx264.so.148 找个这个文件的目录,使用vim /etc/ld.so.conf命令,将目录添加进这个/etc/ld.so.conf文件

          猜想:将库目录添加到 /etc/ld.so.conf ,系统就可以找到此目录下的库文件,估计和windows下配置环境变量是一个效果

         记得最后一定要用命令 ldconfig 重新加载配置文件,否则还会找不到库文件 

   源码:

       

public class ConverVideo {
    private final static Logger LOG = LoggerFactory.getLogger(ConverVideo.class);
    private Date dt;
    private long begintime;
    private String PATH;
    private String filerealname; // 文件名 不包括扩展名
    private String filename; // 包括扩展名
    private String flvfolder; // 转码后视频的目录
    private String ffmpegpath = "ffmpeg"; // ffmpeg.exe的目录


    public ConverVideo() {
    }

    public ConverVideo(String path) {
        PATH = path;
    }

    /**
     * @param PATH      需要转码的文件目录
     * @param flvfolder 转换后的存储目录
     */
    public ConverVideo(String PATH, String flvfolder) {
        this.PATH = PATH;
        this.flvfolder = flvfolder;
    }

    public String getPATH() {
        return PATH;
    }

    public void setPATH(String path) {
        PATH = path;
    }


    public boolean beginConver() {
        //此前配置绝对路径,后经设置环境变量后可省略 路径 例:d:/ffmpeg/bin/ffmpeg.exe
        //String winFfmpegPath = "ffmpeg";
        //String linuxFfmpegPath = "ffmpeg";
        //String systemType = System.getProperty("os.name");
        //ffmpegpath = (systemType.toLowerCase().indexOf("win") == -1) ? linuxFfmpegPath : winFfmpegPath;
        File fi = new File(PATH);
        filename = fi.getName();
        filerealname = filename.substring(0, filename.lastIndexOf(".")).toLowerCase();
        LOG.debug("------------接收到文件(" + PATH + ")需要转换------------ ");
        if (!checkfile(PATH)) {
            LOG.debug(PATH + "文件不存在" + " ");
            return false;
        }
        dt = new Date();
        begintime = dt.getTime();
        LOG.debug("----------------开始转文件(" + PATH + ")--------------- ");
        if (process()) {
            Date dt2 = new Date();
            long endtime = dt2.getTime();
            long timecha = (endtime - begintime);
            String totaltime = sumTime(timecha);
            LOG.debug("-----------------转换成功,共用了:" + totaltime + "  --------------");
            PATH = null;
            return true;
        } else {
            PATH = null;
            return false;
        }
    }

    private boolean process() {
        int type = checkContentType();
        boolean status = false;
        if (type == 0) {
            status = processMP4(PATH);
        }
        return status;
    }

    private int checkContentType() {
        String type = PATH.substring(PATH.lastIndexOf(".") + 1, PATH.length())
                .toLowerCase();
        // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
        //type = 0 ffmpeg可解析;type= 1ffmpeg不可解析,先使用mencoder转为AVI格式
        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("dav")) {
            return 0;
        } else if (type.equals("wmv9")) {
            return 1;
        } else if (type.equals("rm")) {
            return 1;
        } else if (type.equals("rmvb")) {
            return 1;
        } else if (type.equals("dav")) {
            return 1;
        }
        return 9;
    }

    private boolean checkfile(String path) {
        File file = new File(path);
        if (!file.isFile()) {
            return false;
        }
        return true;
    }

    // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
    private boolean processFLV(String oldfilepath) {

        if (!checkfile(PATH)) {
            LOG.debug("--------------" + 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");
        commend.add("-r");
        commend.add("24");
        commend.add("-y");
        commend.add(flvfolder + filerealname + ".flv");
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            Process p = builder.start();
            doWaitFor(p);
            p.destroy();
            deleteFile(oldfilepath);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //转码为MP4格式
    private boolean processMP4(String oldfilepath) {

        if (!checkfile(PATH)) {
            LOG.debug("--------------" + oldfilepath + " is not file");
            return false;
        }
        File tempFile = new File(flvfolder);

        //  path = flvfolder.substring(0, flvfolder.lastIndexOf("/"));
        String path = tempFile.getParent();
        File file = new File(path);
        if (!file.exists())
            file.mkdirs();
        List commend = new ArrayList();
        //FFMPEG  -i  uploadfile/video/test.wmv -c:v libx264 -strict -2 uploadfile/mp4/test.mp4
        String systemType = System.getProperty("os.name");
        if (systemType.toLowerCase().indexOf("win") != -1)
            flvfolder = flvfolder.substring(1);
        commend.add(ffmpegpath);
        commend.add("-i");
        commend.add(oldfilepath);
        commend.add("-c:v");
        commend.add("libx264");
        commend.add("-strict");
        commend.add("-2");
        commend.add(flvfolder);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            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 p is finished
        try {
            in = p.getInputStream();
            err = p.getErrorStream();
            boolean finished = false; // Set to true when p is finished

            while (!finished) {
                try {
                    while (in.available() > 0) {
                        Character c = new Character((char) in.read());
                        //LOG.debug("-----------"+c);
                    }
                    while (err.available() > 0) {
                        Character c = new Character((char) err.read());
                        //LOG.debug("-----------"+c);
                    }

                    exitValue = p.exitValue();
                    finished = true;

                } catch (IllegalThreadStateException e) {
                    Thread.currentThread().sleep(500);
                }
            }
        } catch (Exception e) {
            LOG.error("doWaitFor();: unexpected exception - "
                    + e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                LOG.debug(e.getMessage());
            }
            if (err != null) {
                try {
                    err.close();
                } catch (IOException e) {
                    LOG.debug(e.getMessage());
                }
            }
        }
        return exitValue;
    }

    public void deleteFile(String filepath) {
        File file = new File(filepath);
        if (PATH.equals(filepath)) {
            if (file.delete()) {
                LOG.debug("文件" + filepath + "已删除");
            }
        } else {
            if (file.delete()) {
                LOG.debug("文件" + filepath + "已删除 ");
            }
            File filedelete2 = new File(PATH);
            if (filedelete2.delete()) {
                LOG.debug("文件" + PATH + "已删除");
            }
        }
    }

    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 + "天";
        String strHour = hour < 10 ? "0" + hour + "小时" : "" + hour + "小时";
        String strMinute = minute < 10 ? "0" + minute + "分" : "" + minute + "分";
        String strSecond = second < 10 ? "0" + second + "秒" : "" + second + "秒";
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : ""
                + milliSecond;
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond + "毫秒" : ""
                + strMilliSecond + " 毫秒";
        return strDay + " " + strHour + ":" + strMinute + ":" + strSecond + " "
                + strMilliSecond;

    }
}


调用方法:   

                String convertFilePath = "e:456.dav"; //需要转换的视频目录
                String savePath = "e:/123.mp4"; //转换后保存的文件
                ConverVideo cv = new ConverVideo(convertFilePath, savePath);
                convert = cv.beginConver();

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值