文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java实现视频转码工具类

2024-04-02 19:55

关注

废话不多说,直接上代码:

这是转码工具类:

package com.gcsoft.pyas.sysbase.utils;
import com.gcsoft.pyas.AppProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
public class ConverVideoUtils {
    @Autowired
    private AppProperties appProperties;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    public String beginConver(String sourceVideoPath) {
        //转码格式
        String targetExtension = appProperties.getVideoFormat();
        //是否删除原文件
        Boolean isDeleteResult = appProperties.getIsDeleteResult();
        File fi = new File(sourceVideoPath);
        String fileName = fi.getName();
        //文件名不带扩展名
        String fileRealName = fileName.substring(0, fileName.lastIndexOf("."));
        logger.info("接收到文件(" + sourceVideoPath + ")需要转换");
        if (!checkfile(sourceVideoPath)) {
            logger.error(sourceVideoPath + "文件不存在" + " ");
            return "";
        }
        long beginTime = System.currentTimeMillis();
        logger.info("开始转文件(" + sourceVideoPath + ")");
        String path = process(fileRealName, sourceVideoPath, targetExtension, isDeleteResult);
        if (StringUtil.isNotEmpty(path)) {
            logger.info("转换成功");
            long endTime = System.currentTimeMillis();
            long timeCha = (endTime - beginTime);
            String totalTime = sumTime(timeCha);
            logger.info("转换视频格式共用了:" + totalTime + " ");
            if (isDeleteResult) {
                deleteFile(sourceVideoPath);
            }
            return path;
        } else {
            return "";
        }
    }
    
    private String process(String fileRealName, String sourceVideoPath, String targetExtension, boolean isDeleteResult) {
        int type = checkContentType(sourceVideoPath);
        String path = "";
        if (type == 0) {
            //如果type为0用ffmpeg直接转换
            path = processVideoFormat(sourceVideoPath, fileRealName, targetExtension, isDeleteResult);
        } else if (type == 1) {
            //如果type为1,将其他文件先转换为avi,然后在用ffmpeg转换为指定格式
            String aviFilePath = processAVI(fileRealName, sourceVideoPath);
            if (aviFilePath == null) {
                // avi文件没有得到
                return "";
            } else {
                logger.info("开始转换:");
                path = processVideoFormat(aviFilePath, fileRealName, targetExtension, isDeleteResult);
                if (isDeleteResult) {
                    deleteFile(aviFilePath);
                }
            }
        }
        return path;
    }
    
    private int checkContentType(String sourceVideoPath) {
        String type = sourceVideoPath.substring(sourceVideoPath.lastIndexOf(".") + 1).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;
    }
    
    private boolean checkfile(String path) {
        File file = new File(path);
        if (!file.isFile()) {
            return false;
        } else {
            return true;
        }
    }
    
    private String processAVI(String fileRealName, String sourceVideoPath) {
        
        String menCoderPath = appProperties.getMencoderPath();
        
        String videoFolder = appProperties.getUploadAndFormatPath();
        List<String> commend = new java.util.ArrayList<>();
        commend.add(menCoderPath);
        commend.add(sourceVideoPath);
        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");
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            Process p = builder.start();
            doWaitFor(p);
            return videoFolder + fileRealName + ".avi";
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private String processVideoFormat(String oldFilePath, String fileRealName, String targetExtension, Boolean isDeleteResult) {
        
        String ffmpegPath = appProperties.getFfmpegPath();
        
        String targetFolder = appProperties.getUploadAndFormatPath();
        if (!checkfile(oldFilePath)) {
            logger.error(oldFilePath + "文件不存在");
            return "";
        }
        List<String> commend = new ArrayList<>();
        commend.add(ffmpegPath);
        commend.add("-i");
        commend.add(oldFilePath);
        commend.add("-vcodec");
        commend.add("mpeg4");
        commend.add("-q");
        commend.add("0");
        commend.add("-y");
        commend.add(targetFolder + fileRealName + targetExtension);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            Process p = builder.start();
            doWaitFor(p);
            p.destroy();
            String videoPath = targetFolder + fileRealName + targetExtension;
            String path = this.processVideoFormatH264(videoPath, ffmpegPath, targetFolder, targetExtension, isDeleteResult);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    private String processVideoFormatH264(String path, String ffmpegPath, String targetFolder, String targetExtension, Boolean isDeleteResult) {
        if (!checkfile(path)) {
            logger.error(path + "文件不存在");
            return "";
        }
        String newFilePath = targetFolder + UUID.randomUUID().toString() + targetExtension;
        List<String> commend = new ArrayList<>();
        commend.add(ffmpegPath);
        commend.add("-i");
        commend.add(path);
        commend.add("-vcodec");
        commend.add("h264");
        commend.add("-q");
        commend.add("0");
        commend.add("-y");
        commend.add(newFilePath);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            Process p = builder.start();
            doWaitFor(p);
            p.destroy();
            if (isDeleteResult) {
                deleteFile(path);
            }
            return newFilePath;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    public int doWaitFor(Process p) {
        InputStream in = null;
        InputStream err = null;
        int exitValue = -1;
        try {
            in = p.getInputStream();
            err = p.getErrorStream();
            boolean finished = false;
            while (!finished) {
                try {
                    while (in.available() > 0) {
                        in.read();
                    }
                    while (err.available() > 0) {
                        err.read();
                    }
                    exitValue = p.exitValue();
                    finished = true;
                } catch (IllegalThreadStateException e) {
                    Thread.sleep(500);
                }
            }
        } catch (Exception e) {
            logger.error("doWaitFor();: unexpected exception - " + e.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.info(e.getMessage());
            }
            if (err != null) {
                try {
                    err.close();
                } catch (IOException e) {
                    logger.info(e.getMessage());
                }
            }
        }
        return exitValue;
    }
    
    public void deleteFile(String filepath) {
        File file = new File(filepath);
        if (file.delete()) {
            logger.info("文件" + filepath + "已删除");
        }
    }
    
    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;
    }
}

工具类用到的参数

#视频上传和转码后存放的位置
video.trans.coding=D:/PYAS/TMS/upload/video/
#ffmpeg地址
tool.ffmpeg.path=D:/FFmpeg/ffmpeg.exe
#mencoder地址
tool.mencoder.path=D:/FFmpeg/mencoder.exe
#转码格式
video.format=.mp4
#是否删除源文件
video.isdelete.result=false

工具类用到的转码工具分别是:

  ffmpeg、mencoder

转码工具下载

到此这篇关于java实现视频转码的文章就介绍到这了,更多相关java视频转码内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯