ffmpeg把视频文件转码为MP4格式

windows系统需要下载ffmpeg软件,并在代码中指定路径

centos系统需要安装ffmepg是可执行的命令

java 复制代码
package com.xkj.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ConvertVideoUtils {

    //需要转码的视频的全地址
    private String inputPath;

    //转码后文件的目录
    private String outputPath;

    //ffmpeg文件的路径,linux下无需配置
    private String ffmpegPath;

    //转码后文件的名称
    private String fileName;

    public ConvertVideoUtils(String inputPath, String outputPath, String ffmpegPath, String fileName) {
        log.info("开始转码.....");
        log.info("inputPath={}", inputPath);
        log.info("outputPath={}", outputPath);
        log.info("fileName={}", fileName);
        log.info("ffmpegPath={}", ffmpegPath);
        this.inputPath = inputPath;
        this.outputPath = outputPath;
        this.ffmpegPath = ffmpegPath;
        this.fileName = fileName;
    }

    public static boolean process(String inputPath, String ffmpegPath, String outputPath, String fileName) {
        int type = checkContentType(inputPath);
        boolean status = false;
        log.info("直接转成mp4格式");
        status = processMp4(inputPath, ffmpegPath, outputPath, fileName);// 直接转成mp4格式
        return status;
    }

    private static int checkContentType(String inputPath) {
        String type = inputPath.substring(inputPath.lastIndexOf(".") + 1, inputPath.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;
    }

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

    private static boolean processMp4(String oldfilepath, String ffmpegPath, String outputPath, String fileName) {
        if (!checkfile(oldfilepath)) {
            log.info(oldfilepath + " is not file");
            return false;
        }
        String systemName = getSystemName();
        if (systemName.contains("windows")) { //windows系统
            ffmpegPath = ffmpegPath + "ffmpeg.exe";
        } else {
            ffmpegPath = ffmpegPath + "ffmpeg";
        }
        List<String> command = new ArrayList<>();
        command.add(ffmpegPath);
        command.add("-i");
        command.add(oldfilepath);
        command.add("-c:v");
        command.add("libx264");
        command.add("-mbd");
        command.add("0");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("-2");
        command.add("-pix_fmt");
        command.add("yuv420p");
        command.add("-movflags");
        command.add("faststart");
        command.add(outputPath + fileName + ".mp4");
        log.info("生成的command={}", command);
        try {
            if (systemName.contains("windows")) { //windows系统
                Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
                threadExec(videoProcess.getErrorStream());
                threadExec(videoProcess.getInputStream());
                videoProcess.waitFor();
            } else {
                log.info("linux开始");
                StringBuilder test = new StringBuilder();
                for (String s : command) test.append(s).append(" ");
                log.info(test.toString());
                // 执行命令
                Process p = Runtime.getRuntime().exec(test.toString());
                // 取得命令结果的输出流
                InputStream fis = p.getInputStream();
                // 用一个读输出流类去读
                InputStreamReader isr = new InputStreamReader(fis);
                // 用缓冲器读行
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                // 直到读完为止
                while ((line = br.readLine()) != null) {
                    log.info("视频转换:{}", line);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取系统平台名称:windows、linux...
     */
    private static String getSystemName() {
        return System.getProperty("os.name").toLowerCase();
    }

    /**
     * 分线程执行
     *
     * @param input 输入流
     */
    private static void threadExec(final InputStream input) {
        new Thread(() -> {
            String line;
            try (InputStreamReader inputStreamReader = new InputStreamReader(input);
                 BufferedReader bf = new BufferedReader(inputStreamReader)) {
                while (null != (line = bf.readLine())) {
                    log.info(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public Boolean setVoidInfos() {
        if (!checkfile(inputPath)) {
            log.info(inputPath + " is not file");
            return false;
        }
        if (process(inputPath, ffmpegPath, outputPath, fileName)) {
            log.info("ok");
            return true;
        }
        return false;
    }
}
相关推荐
七夜zippoe5 小时前
WorkBuddy 制作AI武侠短片实战:无 ffmpeg 的 OpenCV 拼接实战
人工智能·opencv·ai·ffmpeg·视频·workbuddy
FlightYe17 小时前
音视频修炼之容器与协议(七):HTTP-MP4 / HTTP-FLV
linux·网络·网络协议·http·ffmpeg·音视频
Android系统攻城狮1 天前
FFmpeg深度解析之av_bsf_get_by_name:如何查找码流过滤器?(七十九)
linux·运维·ffmpeg·音视频进阶·ffmpeg音视频
一木 之林1 天前
SDL双义辨析-CSDN成稿
网络·ffmpeg·sdl
Haooog2 天前
三段视频拼完少了 1 秒?实测 FFmpeg Skill 的淡化与硬切
ffmpeg·自动化·agent·视频剪辑·agent skills
Android系统攻城狮2 天前
FFmpeg深度解析之av_codec_iterate:如何遍历音视频编解码器?(七十八)
linux·运维·ffmpeg·音视频·1024程序员节·音视频进阶
橘色的喵8 天前
Linux V4L2 在 SoC 上取流的四件事:设备节点、缓冲队列、DMA-buf、零拷贝管线
ffmpeg·零拷贝·v4l2·gstreamer·dma-buf·uvc
matianlongg11 天前
实战工具:用 ffmpeg-skill 在本地给编码 Agent 装上视频编辑器
ffmpeg·视频编辑·agent skill·ffmpeg-skill·本地剪辑
JonaHu12 天前
博客转视频总返工?用章节清单、样片和 FFmpeg 搭一条可控流水线
ffmpeg·ai视频·内容创作·acedatacloud
StarsGreen17 天前
ffmpeg中常用结构体以及函数简介以及版本变化情况
ffmpeg