当前位置: 首页 > news >正文

ffmpeg使用及java操作

1.文档

官网: FFmpeg
官方使用文档: ffmpeg Documentation

中文简介: https://www.cnblogs.com/leisure_chn/p/10297002.html

函数及时间: ffmpeg日记1011-过滤器-语法高阶,逻辑,函数使用_ffmpeg gte(t,2)-CSDN博客

java集成ffmpeg: SpringBoot集成ffmpeg实现视频转码播放_jave-all-deps-CSDN博客 

2.命令

快速复制视频片段
ffmpeg -ss 00:00:40 -i test.mp4 -to 00:01:00 -c:v copy -c:a copy  testOutput40.mp4复制视频片段,并调整视频质量,crf一般为23,crf越大压缩越厉害,质量下降越多
ffmpeg -i test.mp4 -ss 00:30 -to 00:50 -c:v libx264 -crf 23 newTest1.mp4调整视频分辨率(调整的分辨率超过原来的,不能提升画质)
ffmpeg -i test.mp4 -vf scale=432:240 video_240p.mp4 -hide_banner
ffmpeg -i test.mp4 -vf scale=-1:240 video_240p.mp4 -hide_banner加水印(10:10水印距离左上角的像素距离)
ffmpeg -i test.mp4 -i used100.png -filter_complex "overlay=10:10" testOutputWater.mp4--保真加水印,不怎么改变视频编码及质量
ffmpeg -i test.mp4 -i used100.png -filter_complex "overlay=10:10" -c:v libx264 -c:a copy testOutputWater2.mp4--视频2秒后开始显示水印,gte(t\,2)
ffmpeg -i test.mp4 -vf "movie=used100.png[logo];[in][logo]overlay=x='if(gte(t\,2)\,0\,NAN)'" testOutputWater6.mp4--在指定时间范围(20-30秒)显示水印,between(t\,20\,30)
ffmpeg -i test.mp4 -vf "movie=used100.png[logo];[in][logo]overlay=x='if(between(t\,20\,30)\,0\,NAN)'" testOutputWater9.mp4加硬字幕
ffmpeg -i test.mp4 -vf subtitles=test.srt mp4_add_captions1.mp4

3.java代码

        maven依赖,使用集成的ffmpeg程序,缺点是打成的jar包很大,优点是不需要手动安装ffmpeg

        <!--   音视频   --><dependency><groupId>ws.schild</groupId><artifactId>jave-all-deps</artifactId><version>3.0.1</version><exclusions><!--  排除windows 32位系统      --><exclusion><groupId>ws.schild</groupId><artifactId>jave-nativebin-win32</artifactId></exclusion><!--  排除linux 32位系统      --><exclusion><groupId>ws.schild</groupId><artifactId>jave-nativebin-linux32</artifactId></exclusion><!-- 排除Mac系统--><exclusion><groupId>ws.schild</groupId><artifactId>jave-nativebin-osx64</artifactId></exclusion></exclusions></dependency>

          第二种方式,不引入集成的ffmpeg,手动在程序运行的服务器上安,优点是打成的jar包较小,关于如何手动在服务器上配置ffmpeg,请见附录2

        <!--音视频操作--><dependency><groupId>ws.schild</groupId><artifactId>jave-core</artifactId><version>3.0.1</version></dependency>

        工具类

package mis.shared.file;import lombok.extern.slf4j.Slf4j;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.MultimediaInfo;
import ws.schild.jave.process.ProcessWrapper;
import ws.schild.jave.process.ffmpeg.DefaultFFMPEGLocator;import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;/*** 音视频操作** @since 2024/1/22*/
@Slf4j
public class FfmpegUtil {/*** 通过本地路径获取多媒体文件信息(宽,高,时长,编码等)** @param localPath 文件路径* @return MultimediaInfo 媒体对象,包含 (宽,高,时长,编码等)*/public static MultimediaInfo GetMediaInfo(String localPath) {MultimediaInfo multimediaInfo = null;try {multimediaInfo = new MultimediaObject(new File(localPath)).getInfo();} catch (EncoderException e) {log.error("获取媒体信息异常!", e);}return multimediaInfo;}/*** 修改视频分辨率,修改分辨率超过原视频,不能提高画质* 标清SD(Standard Definition) 宽 x 高* 480p 640x480 704x480 720x480 848x480* 高清 HD(High Definition)* 720p 960x720 1280x720* 1080p 1440x1080 1920x1080* 超高清UHD(Ultra High Definition)* 4k 4096×3112 4096*2160** @param inputPath  视频来源地址* @param outputPath 输出视频地址* @param width      宽度* @param height     高度*/public static boolean ChangeScale(String inputPath, String outputPath, int width, int height) {ProcessWrapper ffmpeg = null;try {if (new File(outputPath).exists()) {log.error("目标文件已存在,outputPath:{}", outputPath);return false;}ffmpeg = new DefaultFFMPEGLocator().createExecutor();ffmpeg.addArgument("-i");ffmpeg.addArgument(inputPath);ffmpeg.addArgument("-vf");ffmpeg.addArgument("scale=" + width + ":" + height);ffmpeg.addArgument("-c:a");ffmpeg.addArgument("copy");ffmpeg.addArgument(outputPath);long start = System.currentTimeMillis();//异步执行ffmpeg.execute();//等待完成WaitFfmpegFinish(ffmpeg);log.info("花费时间:{}", System.currentTimeMillis() - start);return true;} catch (Exception e) {log.error("修改视频画质异常", e);} finally {if (ffmpeg != null) {ffmpeg.destroy();}}return false;}/*** 复制视频片段** @param inputPath  视频来源地址* @param outputPath 输出视频地址* @param startTime  开始时间,01:02:03在视频的第1小时第2分钟第3秒处* @param endTime    结束时间,格式同startTime*/public static boolean CopyVideo(String inputPath, String outputPath, String startTime, String endTime) {ProcessWrapper ffmpeg = null;try {if (new File(outputPath).exists()) {log.error("目标文件已存在,outputPath:{}", outputPath);return false;}ffmpeg = new DefaultFFMPEGLocator().createExecutor();ffmpeg.addArgument("-ss");ffmpeg.addArgument(startTime);ffmpeg.addArgument("-i");ffmpeg.addArgument(inputPath);ffmpeg.addArgument("-to");ffmpeg.addArgument(endTime);ffmpeg.addArgument("-c:v");ffmpeg.addArgument("copy");ffmpeg.addArgument("-c:a");ffmpeg.addArgument("copy");ffmpeg.addArgument(outputPath);long start = System.currentTimeMillis();//异步执行ffmpeg.execute();//等待完成WaitFfmpegFinish(ffmpeg);log.info("花费时间:{}", System.currentTimeMillis() - start);return true;} catch (Exception e) {log.error("复制视频片段异常", e);} finally {if (ffmpeg != null) {ffmpeg.destroy();}}return false;}/*** 视频格式转换为mp4*/public static boolean FormatToMp4(String localPath, String outputPath) {try {File target = new File(outputPath);if (target.exists()) {log.error("目标文件已存在,outputPath:{}", outputPath);return false;}MultimediaObject multimediaObject = new MultimediaObject(new File(localPath));EncodingAttributes attributes = new EncodingAttributes();// 设置视频的音频参数AudioAttributes audioAttributes = new AudioAttributes();attributes.setAudioAttributes(audioAttributes);// 设置视频的视频参数VideoAttributes videoAttributes = new VideoAttributes();// 设置帧率videoAttributes.setFrameRate(25);attributes.setVideoAttributes(videoAttributes);// 设置输出格式attributes.setOutputFormat("mp4");Encoder encoder = new Encoder();encoder.encode(multimediaObject, target, attributes);return true;} catch (Exception e) {log.error("视频转换异常!", e);return false;}}/*** 获取视频缩略图* 获取视频第0秒的第一帧图片*/public static boolean GetThumbnail(String localPath, String outputPath) {ProcessWrapper ffmpeg = null;try {File target = new File(outputPath);if (target.exists()) {log.error("目标文件已存在,outputPath:{}", outputPath);return false;}ffmpeg = new DefaultFFMPEGLocator().createExecutor();ffmpeg.addArgument("-i");ffmpeg.addArgument(localPath);ffmpeg.addArgument("-ss");ffmpeg.addArgument("0");ffmpeg.addArgument(outputPath);ffmpeg.execute();//等待执行完成WaitFfmpegFinish(ffmpeg);} catch (Exception e) {log.error("获取视频缩略图异常", e);return false;} finally {if (ffmpeg != null) {ffmpeg.destroy();}}return true;}/*** 等待命令执行完成*/private static void WaitFfmpegFinish(ProcessWrapper processWrapper) throws Exception {//输出执行情况不是通过inputStream,而是errorStreamtry (BufferedReader br = new BufferedReader(new InputStreamReader(processWrapper.getErrorStream()))) {String processInfo;while ((processInfo = br.readLine()) != null) {//打印执行过程log.trace(processInfo);}} catch (Exception e) {log.error("等待执行完成异常!", e);}}public static void main(String[] args) {String inputFile = "e://develop//tmp//test.mp4";String outputFile = "e://develop//tmp//testOutput14.mp4";//复制视频指定片段CopyVideo(inputFile, outputFile, "00:00:10", "00:01:00");//获取媒体信息// MultimediaInfo multimediaInfo = GetMediaInfo(inputFile);// log.info("文件信息:{}", multimediaInfo);// VideoSize videoSize = multimediaInfo.getVideo().getSize();// log.info("文件信息,宽:{},高:{}", videoSize.getWidth(), videoSize.getHeight());//修改视频画质//ChangeScale(inputFile, outputFile, 640, 480);}}

附录1

         字幕test.srt

1
00:00:20,000 --> 00:00:30,000
这是视频第20秒到30秒将显示的字幕2
00:00:50,000 --> 00:00:60,000
这是视频第50秒到60秒将显示的字幕

附录2

        关于ffmpeg在服务器上的位置,参考如下代码

  public DefaultFFMPEGLocator() {String os = System.getProperty("os.name").toLowerCase();boolean isWindows = os.contains("windows");boolean isMac = os.contains("mac");LOG.debug("Os name is <{}> isWindows: {} isMac: {}", os, isWindows, isMac);// Dir FolderFile dirFolder = new File(System.getProperty("java.io.tmpdir"), "jave/");if (!dirFolder.exists()) {LOG.debug("Creating jave temp folder to place executables in <{}>", dirFolder.getAbsolutePath());dirFolder.mkdirs();} else {LOG.debug("Jave temp folder exists in <{}>", dirFolder.getAbsolutePath());}// -----------------ffmpeg executable export on disk.-----------------------------String suffix = isWindows ? ".exe" : (isMac ? "-osx" : "");String arch = System.getProperty("os.arch");// FileFile ffmpegFile = new File(dirFolder, "ffmpeg-" + arch + "-" + Version.getVersion() + suffix);LOG.debug("Executable path: {}", ffmpegFile.getAbsolutePath());// Check the version of existing .exe fileif (ffmpegFile.exists()) {// OK, already presentLOG.debug("Executable exists in <{}>", ffmpegFile.getAbsolutePath());} else {LOG.debug("Need to copy executable to <{}>", ffmpegFile.getAbsolutePath());copyFile("ffmpeg-" + arch + suffix, ffmpegFile);}// Need a chmod?if (!isWindows) {try {Runtime.getRuntime().exec(new String[] {"/bin/chmod", "755", ffmpegFile.getAbsolutePath()});} catch (IOException e) {LOG.error("Error setting executable via chmod", e);}}// Everything seems okaypath = ffmpegFile.getAbsolutePath();if (ffmpegFile.exists()){LOG.debug("ffmpeg executable found: {}", path);}else{LOG.error("ffmpeg executable NOT found: {}", path);}}

       windows环境,打开cmd窗口,执行echo %TEMP%获取临时文件夹,打开临时文件夹,创建子文件夹jave(最终路径例子C:\Users\TN\AppData\Local\Temp\jave)

        下载ws.schild的maven对应系统jar包,并解压jave-nativebin-win64-3.0.1,找到里面的ffmpeg-amd64.exe复制到上面的目录下

         linux通过脚本获取默认目录,原理是通过编译运行FfmpegHelper.java获得

#!/bin/bashcd /tmp# download 
if [ -e "/tmp/FfmpegHelper.java" ]
thenecho "FfmpegHelper.java already exist!"
elseecho "FfmpegHelper.java does not exist,start download"wget https://fs-im-kefu.7moor-fs1.com/29397395/4d2c3f00-7d4c-11e5-af15-41bf63ae4ea0/1705980395189/FfmpegHelper.java
fi# compile
if [ -e "/tmp/FfmpegHelper.class" ]
thenecho "FfmpegHelper.class already exist!"
elseecho "FfmpegHelper.class does not exist,start compile"javac FfmpegHelper.java
fi# run
java FfmpegHelper# clean
rm -rf /tmp/FfmpegHelper.class
rm -rf /tmp/FfmpegHelper.java

        FfmpegHelper.java

import java.io.File;public class FfmpegHelper {public static String GetDefaultFFMPEGPath() {return new File(System.getProperty("java.io.tmpdir"), "jave/").getAbsolutePath();}public static void main(String[] args) {String defaultFFMPEGPath = GetDefaultFFMPEGPath();System.out.println(defaultFFMPEGPath);}}

相关文章:

  • 自然语言处理--双向匹配算法
  • 【GoLang入门教程】Go语言工程结构详述
  • c#中使用UTF-8编码处理多语言文本的有效策略
  • 设计模式二(工厂模式)
  • Relay Arm® 计算库集成
  • AI大模型【基础 01】智能AI开源模型与大模型接口整理(8个开源模型+7个大模型接口)
  • 南京观海微电子---时序分析基本概念(二)——保持时间
  • 2017年认证杯SPSSPRO杯数学建模A题(第二阶段)安全的后视镜全过程文档及程序
  • C#,入门教程(22)——函数的基础知识
  • RPC和HTTP,它们之间到底啥关系
  • VsCode容器开发 - VsCode连接远程服务器上的docker
  • 【江科大】STM32:(超级详细)定时器输出比较
  • Ebay、SHEIN、亚马逊出口儿童滑梯CE认证标准EN71解析
  • CNAS中兴新支点——商用密码评测:保护信息安全的重要环节
  • 《Python数据分析技术栈》第03章 01 正则表达式(Regular expressions)
  • “Material Design”设计规范在 ComponentOne For WinForm 的全新尝试!
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • JavaScript/HTML5图表开发工具JavaScript Charts v3.19.6发布【附下载】
  • mysql_config not found
  • nginx(二):进阶配置介绍--rewrite用法,压缩,https虚拟主机等
  • Transformer-XL: Unleashing the Potential of Attention Models
  • 笨办法学C 练习34:动态数组
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 更好理解的面向对象的Javascript 1 —— 动态类型和多态
  • 力扣(LeetCode)56
  • 如何使用 OAuth 2.0 将 LinkedIn 集成入 iOS 应用
  • 使用common-codec进行md5加密
  • 一些关于Rust在2019年的思考
  • ​力扣解法汇总946-验证栈序列
  • ​什么是bug?bug的源头在哪里?
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • !$boo在php中什么意思,php前戏
  • # 飞书APP集成平台-数字化落地
  • (2020)Java后端开发----(面试题和笔试题)
  • (webRTC、RecordRTC):navigator.mediaDevices undefined
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (续)使用Django搭建一个完整的项目(Centos7+Nginx)
  • (转)winform之ListView
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • .NET 8.0 中有哪些新的变化?
  • .Net core 6.0 升8.0
  • .net core使用ef 6
  • .NetCore部署微服务(二)
  • .NET开源的一个小而快并且功能强大的 Windows 动态桌面软件 - DreamScene2
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?
  • @ModelAttribute使用详解
  • [ linux ] linux 命令英文全称及解释
  • [2010-8-30]
  • [20150321]索引空块的问题.txt
  • [AndroidStudio]_[初级]_[修改虚拟设备镜像文件的存放位置]
  • [AutoSar]BSW_Memory_Stack_004 创建一个简单NV block并调试
  • [BZOJ4337][BJOI2015]树的同构(树的最小表示法)
  • [CareerCup] 13.1 Print Last K Lines 打印最后K行
  • [CSS]浮动
  • [C进阶] 数据在内存中的存储——浮点型篇