Ffmpeg入门级教程(Java代码开发)

目录

1、简介

2、安装

2.1、下载

2.2、配置环境变量

3、Java调用

3.1、运行CMD命令的类

3.2、工具类

3.2.1视频提取音频

3.2.2音频剪辑

3.2.3视频剪辑

4、总结

附录:


1、简介

FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。采用LGPL或GPL许可证。它提供了录制、转换以及流化音视频的完整解决方案。它包含了非常先进的音频/视频编解码库libavcodec,为了保证高可移植性和编解码质量,libavcodec里很多code都是从头开发的。

FFmpeg在Linux平台下开发,但它同样也可以在其它操作系统环境中编译运行,包括WindowsMac OS X等。

2、安装

2.1、下载

官网下载ffmpeg安装包,官网地址:http://www.ffmpeg.org/download.html

或者直接到这个链接win1064位安装ffmpeg的免安装ZIP包-编解码文档类资源-CSDN文库下载获得ffmpeg安装包,会比官网下载快些。

2.2、配置环境变量

ffmpeg安装包下载成功后,解压至电脑某个路径,复制此文件下bin文件的路径,配置环境变量。

1. bin文件夹路径:E:\Program Files\ffmpeg-master-latest-win64-gpl\bin
2.环境变量配置步骤(以win10举例):

  1)点击“系统属性->高级系统设置->环境变量->用户变量”,选择“Path”条目,点击“编辑->新建”,把第一步的bin文件夹路径复制粘贴进去,然后点击确定即可。
  2)变量设置成功后,打开电脑的命令框,输入:ffmpeg -h  若命令框有如下内容输出则ffmpeg安装成功且设置成功

3、Java调用

ffmpeg的Java调用一般都是采用CMD命令调用本地服务的方式,例如:

ffmpeg -i sourceFilePath.mp3 -ss 409 -t 172 -vn -c:a mp3 -y targetFilePath.mp3

我们后面的调用也是对此类命令进行封装、修改参数的方式进行的。

3.1、运行CMD命令的类

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @date 2022/8/8 10:49
 */
public class RuntimeUtils {


    public static void run(List<String> command){
        try {
            BufferedReader br = null;
            try {
                ProcessBuilder builder = new ProcessBuilder();
                builder.command(command);
                builder.redirectErrorStream(true);
                Process process = builder.start();
                br = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.2、工具类

3.2.1视频提取音频

public static Boolean audioByVideo(String videoSourceFilePath, String audioTargetFilePath) {
        try {
            LOGGER.info("Get Audio By Video Start, Source={}", videoSourceFilePath);
            long beginTime = System.currentTimeMillis();
            File outputFile = new File(audioTargetFilePath);
            if(outputFile.exists()){
                outputFile.delete();
            }
            File outputDir = outputFile.getParentFile();
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            // 执行的命令
            ArrayList<String> command = new ArrayList<>();
            command.add("ffmpeg");
            command.add("-hide_banner");
            command.add("-i");
            command.add(videoSourceFilePath);
            command.add("-vn");
            command.add("-b:a");
            command.add("16k");
            command.add("-c:a");
            command.add("mp3");
            command.add("-y");

            command.add(audioTargetFilePath);
            LOGGER.info("Audio By Video Command = {}", StringUtils.join(command," "));
            RuntimeUtils.run(command);
            long timeConsuming = System.currentTimeMillis() - beginTime;
            LOGGER.info("Audio By Video Run Success, VideoFileName={}, Time Consuming={}s",videoSourceFilePath, timeConsuming/1000);
            return true;
        } catch (Exception e) {
            LOGGER.error("Audio By Video Run Error! VideoFileName={}", videoSourceFilePath, e);
            return false;
        }
    }

3.2.2音频剪辑

public static boolean audioSplit(String sourceFilePath, String targetFilePath, int startSecond,int endSecond) {
        try {
            LOGGER.info("Audio Split Start, Source={}", sourceFilePath);
            long beginTime = System.currentTimeMillis();
            File outputFile = new File(targetFilePath);
            File outputDir = outputFile.getParentFile();
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            // 获取视频总时长,单位:秒
            int duration = endSecond - startSecond; //分割的时长
            /**
             * 执行分割命令,命令参数详解:
             * -i 指定输入文件
             * -c copy 拷贝源视频流,不对源视频进行重新编码,可以加快视频分割速度
             * -ss 指定从什么时间开始
             * -t 指定需要截取多长时间,单位:秒
             */
            ArrayList<String> command = new ArrayList<>();
            command.add("ffmpeg");//ffmpegLocator.getExecutablePath()
            command.add("-hide_banner");
            command.add("-i");
            command.add(sourceFilePath);
            command.add("-ss");
            command.add(startSecond + "");
            command.add("-t");
            command.add(duration+"");
            command.add("-vn");
            command.add("-c:a");
            command.add("mp3");
            command.add("-y");
            command.add(targetFilePath);
            LOGGER.info("Audio Split Command = {}", StringUtils.join(command," "));
            RuntimeUtils.run(command);
            long timeConsuming = System.currentTimeMillis() - beginTime;
            LOGGER.info("Audio Split Success, FileName={}, StartSecond={}, EndSecond={},Time Consuming={}s",
                    sourceFilePath, startSecond, endSecond, timeConsuming/1000);
        } catch (Exception e) {
            LOGGER.error("Audio Split Error, FileName={}, StartSecond={}, EndSecond={}", sourceFilePath, startSecond, endSecond, e);
            return false;
        }
        return true;
    }

3.2.3视频剪辑

public static boolean videoSplit(String sourceFilePath, String targetFilePath, int startSecond,int endSecond) {
        try {
            LOGGER.info("Video Split Start, Source={}", sourceFilePath);
            long beginTime = System.currentTimeMillis();
            File outputDir = outputFile.getParentFile();
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            int duration = endSecond - startSecond; //分割的时长
            /**
             * 执行分割命令,命令参数详解:
             * -i 指定输入文件
             * -ss 指定从什么时间开始
             * -c ... 拷贝源视频流
             * -t 指定需要截取多长时间,单位:秒
             */
            // 执行的命令
            ArrayList<String> command = new ArrayList<>();
            command.add("ffmpeg");//ffmpegLocator.getExecutablePath()
            command.add("-hide_banner");
            command.add("-ss");
            command.add(startSecond+"");
            command.add("-c:v");
            command.add("h264");
            command.add("-c:a");
            command.add("aac");
            command.add("-t");
            command.add(duration+"");
            command.add("-i");
            command.add(sourceFilePath);
            command.add("-y");
            command.add(targetFilePath);
            LOGGER.info("Video Split Command = {}", StringUtils.join(command," "));
            RuntimeUtils.run(command);
            long timeConsuming = System.currentTimeMillis() - beginTime;
            LOGGER.info("Video Split Success, FileName={}, StartSecond={}, EndSecond={},Time Consuming={}s",
                    sourceFilePath, startSecond, endSecond, timeConsuming / 1000);
        } catch (Exception e) {
            LOGGER.error("Video Split Error! FileName={}, StartSecond={}, EndSecond={}", sourceFilePath, startSecond, endSecond, e);
            return false;
        }
        return true;
    }

4、总结

到此这篇关于java使用ffmpeg处理视频的方法的文章就结束了,关于其他的音视频操作可参考相关命令自行拼接cmd命令行。

附录:

FFmpeg常用命令汇总_梧桐樹下的博客-CSDN博客_ffmpeg指令

猜你喜欢

转载自blog.csdn.net/u012998680/article/details/126627715
今日推荐