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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

内核启动时减少log的方式

内核引导选项 内核引导选项大体上可以分为两类:一类与设备无关、另一类与设备有关。与设备有关的引导选项多如牛毛,需要你自己阅读内核中的相应驱动程序源码以获取其能够接受的引导选项。比如,如果你想知道可以向 AHA1542 SCSI 驱动程序传递哪些引导选项,那么就查看 drivers/scsi/aha1542.c 文件,一般在前面 100 行注释里就可以找到所接受的引导选项说明。大多数选项是通过"_