java读取视频文件信息的两种方式(jave、ffmpeg)

2023-10-22 18:59

本文主要是介绍java读取视频文件信息的两种方式(jave、ffmpeg),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、通过Jave的方式读取文件信息
  1. 需要一个jar包
<!-- 获取视频时长等信息 --><dependency><groupId>jave</groupId><artifactId>jave</artifactId><version>1.0.2</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/libs/jave-1.0.2.jar</systemPath></dependency>

在这里插入图片描述
2. java代码实现

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.MultimediaInfo;private void getVideoInfo(String filePath){File source = new File(filePath);Encoder encoder = new Encoder();try{MultimediaInfo mi = encoder.getInfo(source);System.out.println(mi.getVideo()); //视频信息System.out.println(mi.getAudio());  //音频信息String duration = LxTimeUtil.msecToTime(mi.getDuration());int width = mi.getVideo().getSize().getWidth();int height = mi.getVideo().getSize().getHeight();String format = mi.getFormat();int audioChannels = mi.getAudio().getChannels();String audioDecoder = mi.getAudio().getDecoder();int audioSamplingRate = mi.getAudio().getSamplingRate();String videoDecoder = mi.getVideo().getDecoder();float videoFrameRate = mi.getVideo().getFrameRate();System.out.println("★★★★★★★★★【"+source+"】★★★★★★★★★");System.out.println("格式:" + format);System.out.println("时长:" + duration);System.out.println("尺寸:" + width + "×" + height);System.out.println("音频编码:"+ audioDecoder);System.out.println("音频轨道:" + audioChannels);System.out.println("音频采样率:" + audioSamplingRate);System.out.println("视频编码:" + videoDecoder);System.out.println("视频帧率:" + videoFrameRate);//获取视频大小FileInputStream fis = new FileInputStream(source);FileChannel fc= null;fc= fis.getChannel();BigDecimal fileSize = new BigDecimal(fc.size());}catch (Exception e) {e.printStackTrace();} finally {if (null != fc) {try {fc.close();} catch (IOException e) {e.printStackTrace();}}}
}
二、通过ffmpeg的方式读取文件信息(项目中的webm视频格式通过jave解析不了,最终换成ffmpeg)
  1. 首先本地要下载ffmpeg
    http://www.ffmpeg.org/download.html
    在这里插入图片描述
  2. 随后在环境变量中配置ffmpeg
    在这里插入图片描述
    测试是否成功读取文件信息
    在这里插入图片描述
  3. java代码实现
    首先引入pom文件
<dependency><groupId>oro</groupId><artifactId>oro</artifactId><version>2.0.8</version></dependency><dependency><groupId>com.alibaba.druid</groupId><artifactId>druid-wrapper</artifactId><version>0.2.9</version></dependency>
import org.apache.commons.lang3.StringUtils;
import org.apache.oro.text.regex.*;import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public static Map getEncodingFormat(String filePath) throws IOException {String cut = "ffmpeg -i "+ filePath;String command = "" + cut;System.out.println(command);Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});InputStream in = process.getErrorStream();BufferedReader br = new BufferedReader(new InputStreamReader(in));String line;StringBuffer sb = new StringBuffer();String fps = null;FileChannel fc = null;while ((line = br.readLine()) != null) {sb.append(line);if (line.contains("fps")) {String[] split = line.split(",");for (String d : split) {if (d.contains("fps")) {String[] split1 = d.split(" fps"); //提取视频文件的fpsfps = split1[0].trim();}}}continue;}String processFLVResult = sb.toString();Map retMap = new HashMap();retMap.put("fps", fps);if (org.apache.commons.lang3.StringUtils.isNotBlank(processFLVResult)) {PatternCompiler compiler = new Perl5Compiler();try {File source = new File(filePath);FileInputStream fis = new FileInputStream(source);fc = fis.getChannel();retMap.put("size", fc.size());String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";String regexVideo = "Video: (.*?), (.*?\\)), (.*?)[,\\s]";String regexAudio = "Audio: (\\w*), (\\d*) Hz";Pattern patternDuration = compiler.compile(regexDuration, Perl5Compiler.CASE_INSENSITIVE_MASK);PatternMatcher matcherDuration = new Perl5Matcher();if (matcherDuration.contains(processFLVResult, patternDuration)) {MatchResult re = matcherDuration.getMatch();retMap.put("提取出播放时间", re.group(1));String[] split = re.group(1).split(":");String s = split[0];Integer a = Integer.parseInt(s) * 60;String s1 = split[1];Integer a1 = Integer.parseInt(s1) * 60;Integer a2 = Integer.valueOf(split[2].split("\\.")[0]);Integer w = a + a1 + a2;retMap.put("duration", w);retMap.put("开始时间", re.group(2));retMap.put("bitrate", re.group(3));}Pattern patternVideo = compiler.compile(regexVideo, Perl5Compiler.CASE_INSENSITIVE_MASK);PatternMatcher matcherVideo = new Perl5Matcher();if (matcherVideo.contains(processFLVResult, patternVideo)) {MatchResult re = matcherVideo.getMatch();retMap.put("codec", re.group(1).split("\\(")[0].trim());retMap.put("format", re.group(2).split("\\(")[0]);retMap.put("width", re.group(3).split("x")[0]);retMap.put("height", re.group(3).split("x")[1]);}} catch (MalformedPatternException e) {e.printStackTrace();}finally {if (null!=fc){try {fc.close();} catch (IOException e) {e.printStackTrace();}}}}return retMap;}//linux方式下的读取方式 (因为项目是用docker部署的,所以读取的视频文件是在容器内部,所以得用这种方式读取)public static String processFLV(String filePath) {String cut1 = "ffmpeg -i "+ filePath;try {String command = "" + cut1;System.out.println(command);Process process = Runtime.getRuntime().exec(new String[]{"sh","-c",command});InputStream in = process.getErrorStream();BufferedReader br = new BufferedReader(new InputStreamReader(in));String line ;StringBuffer sb1 = new StringBuffer();while ((line = br.readLine()) != null) {sb1.append(line);if(line.contains("fps")){String[] split = line.split(",");for (String d : split) {if(d.contains("fps")){String[] split1 = d.split(" fps");String fps1 = split1[0];}}}continue;}System.out.println(sb1.toString());return sb1.toString();}catch (IOException e) {e.printStackTrace();return null;}}//windows环境下读取方式 public static String processFLVWin(String filePath) {//注意要保留单词之间有空格List commend = new java.util.ArrayList();commend.add("D:\\xbb\\ffmpeg-N-104863-g6cf55b9da2-win64-gpl-shared\\ffmpeg-N-104863-g6cf55b9da2-win64-gpl-shared\\bin\\ffmpeg.exe");//可以设置环境变量从而省去这行commend.add("ffmpeg");commend.add("-i");commend.add(filePath);try {ProcessBuilder builder = new ProcessBuilder();builder.command(commend);builder.redirectErrorStream(true);Process p = builder.start();BufferedReader buf = null;String line = null;buf = new BufferedReader(new InputStreamReader(p.getInputStream()));StringBuffer sb = new StringBuffer();while ((line = buf.readLine()) != null) {System.out.println(line);sb.append(line);if(line.contains("fps")){String[] split = line.split(",");for (String d : split) {if(d.contains("fps")){String[] split1 = d.split(" fps");String fps = split1[0];}}}continue;}int ret = p.waitFor();return sb.toString();} catch (IOException | InterruptedException e) {e.printStackTrace();return null;}}

参考博客:https://www.cnblogs.com/xhy-shine/p/11820341.html

这篇关于java读取视频文件信息的两种方式(jave、ffmpeg)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/263038

相关文章

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

Java字符串操作技巧之语法、示例与应用场景分析

《Java字符串操作技巧之语法、示例与应用场景分析》在Java算法题和日常开发中,字符串处理是必备的核心技能,本文全面梳理Java中字符串的常用操作语法,结合代码示例、应用场景和避坑指南,可快速掌握字... 目录引言1. 基础操作1.1 创建字符串1.2 获取长度1.3 访问字符2. 字符串处理2.1 子字

Java Optional的使用技巧与最佳实践

《JavaOptional的使用技巧与最佳实践》在Java中,Optional是用于优雅处理null的容器类,其核心目标是显式提醒开发者处理空值场景,避免NullPointerExce... 目录一、Optional 的核心用途二、使用技巧与最佳实践三、常见误区与反模式四、替代方案与扩展五、总结在 Java

基于Java实现回调监听工具类

《基于Java实现回调监听工具类》这篇文章主要为大家详细介绍了如何基于Java实现一个回调监听工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录监听接口类 Listenable实际用法打印结果首先,会用到 函数式接口 Consumer, 通过这个可以解耦回调方法,下面先写一个

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

Java字符串处理全解析(String、StringBuilder与StringBuffer)

《Java字符串处理全解析(String、StringBuilder与StringBuffer)》:本文主要介绍Java字符串处理全解析(String、StringBuilder与StringBu... 目录Java字符串处理全解析:String、StringBuilder与StringBuffer一、St

springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法

《springboot整合阿里云百炼DeepSeek实现sse流式打印的操作方法》:本文主要介绍springboot整合阿里云百炼DeepSeek实现sse流式打印,本文给大家介绍的非常详细,对大... 目录1.开通阿里云百炼,获取到key2.新建SpringBoot项目3.工具类4.启动类5.测试类6.测

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

在Spring Boot中浅尝内存泄漏的实战记录

《在SpringBoot中浅尝内存泄漏的实战记录》本文给大家分享在SpringBoot中浅尝内存泄漏的实战记录,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录使用静态集合持有对象引用,阻止GC回收关键点:可执行代码:验证:1,运行程序(启动时添加JVM参数限制堆大小):2,访问 htt