FFmpeg获取视频详情

话不多说,直接上代码:

pom依赖:

        <!--视频多媒体工具包 包含 FFmpeg、OpenCV--><dependency><groupId>org.bytedeco</groupId><artifactId>javacv-platform</artifactId><version>1.5.3</version></dependency><!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.openjfx</groupId><artifactId>javafx-controls</artifactId><version>16</version></dependency>

工具类:

package com.example.mybatisdemo02.util;import com.example.mybatisdemo02.model.VideoInfoVO;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import org.apache.commons.lang.StringUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import javafx.scene.control.Button;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.UUID;public class FFmpegUtil {private static final String IMAGE_SUFFIX = "png";/*** 获取视频时长,单位为秒S* @return*/public static long getVideoTime( String localPath) throws FrameGrabber.Exception {
//        String localPath = "C:/Users/Administrator/Desktop/dab2d14cad0244229e228e7bf297dd9a.flv";FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(localPath);grabber.start();long duration = grabber.getLengthInTime() / (1000 * 1000);grabber.stop();System.out.println("此视频时长(s/秒):"+duration);return duration;}/*** 获取视频帧图片* @param file 视频源* @param number 第几帧* @param dir 文件存放根目录* @param args 文件存放根目录* @return*/@SuppressWarnings("resource")public static String videoImage(File file, Integer number, String dir, String args) {String picPath = StringUtils.EMPTY;FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);try {ff.start();int i = 0;int length = ff.getLengthInFrames();Frame frame = null;while (i < length) {frame = ff.grabFrame();//截取第几帧图片if ((i > number) && (frame.image != null)) {//获取生成图片的路径picPath = getImagePath(args);//执行截图并放入指定位置doExecuteFrame(frame, dir + File.separator + picPath);break;}i++;}ff.stop();} catch (FrameGrabber.Exception e) {e.printStackTrace();}return picPath;}/*** 截取缩略图* @param frame* @param targerFilePath 图片存放路径*/public static void doExecuteFrame(Frame frame, String targerFilePath) {//截取的图片if (null == frame || null == frame.image) {return;}Java2DFrameConverter converter = new Java2DFrameConverter();BufferedImage srcImage = converter.getBufferedImage(frame);int srcImageWidth = srcImage.getWidth();int srcImageHeight = srcImage.getHeight();//对帧图片进行等比例缩放(缩略图)int width = 480;int height = (int) (((double) width / srcImageWidth) * srcImageHeight);BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);File output = new File(targerFilePath);try {ImageIO.write(thumbnailImage, IMAGE_SUFFIX, output);} catch (IOException e) {e.printStackTrace();}}/*** 生成图片的相对路径* @param args 传入生成图片的名称、为空则用UUID命名* @return 例如 upload/images.png*/public static String getImagePath(String args) {if (StringUtils.isNotEmpty(args)) {return args + "." + IMAGE_SUFFIX;}return getUUID() + "." + IMAGE_SUFFIX;}/*** 生成唯一的uuid* @return uuid*/public static String getUUID(){return UUID.randomUUID().toString().replace("-","");}/*** 时长格式换算* @param duration 时长* @return HH:mm:ss*/public static String formatDuration(Long duration) {String formatTime = StringUtils.EMPTY;double time = Double.valueOf(duration);if (time > -1) {int hour = (int) Math.floor(time / 3600);int minute = (int) (Math.floor(time / 60) % 60);int second = (int) (time % 60);if (hour < 10) {formatTime = "0";}formatTime += hour + ":";if (minute < 10) {formatTime += "0";}formatTime += minute + ":";if (second < 10) {formatTime += "0";}formatTime += second;}return formatTime;}/*** 获取图片大小Kb* @param urlPath* @return*/public static String getImageSize(String urlPath){// 得到数据byte[] imageFromURL = getImageFromURL(urlPath);// 转换String byte2kb = bytes2kb(imageFromURL.length);return byte2kb;}/*** 根据图片地址获取图片信息** @param urlPath 网络图片地址* @return*/public static byte[] getImageFromURL(String urlPath) {// 字节数组byte[] data = null;// 输入流InputStream is = null;// Http连接对象HttpURLConnection conn = null;try {// Url对象URL url = new URL(urlPath);// 打开连接conn = (HttpURLConnection) url.openConnection();// 打开读取 写入是setDoOutput
//	        conn.setDoOutput(true);conn.setDoInput(true);// 设置请求方式conn.setRequestMethod("GET");// 设置超时时间conn.setConnectTimeout(6000);// 得到访问的数据流is = conn.getInputStream();// 验证访问状态是否是200 正常if (conn.getResponseCode() == 200) {data = readInputStream(is);} else {data = null;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (is != null) {// 关闭流is.close();}} catch (IOException e) {e.printStackTrace();}// 关闭连接conn.disconnect();}return data;}/*** 将流转换为字节** @param is* @return*/public static byte[] readInputStream(InputStream is) {/*** 捕获内存缓冲区的数据,转换成字节数组* ByteArrayOutputStream类是在创建它的实例时,程序内部创建一个byte型别数组的缓冲区,然后利用ByteArrayOutputStream和ByteArrayInputStream的实例向数组中写入或读出byte型数据。* 在网络传输中我们往往要传输很多变量,我们可以利用ByteArrayOutputStream把所有的变量收集到一起,然后一次性把数据发送出去。*/ByteArrayOutputStream baos = new ByteArrayOutputStream();// 创建字节数组 1024 = 1Mbyte[] buffer = new byte[1024];// 防止无限循环int length = -1;try {// 循环写入数据到字节数组while ((length = is.read(buffer)) != -1) {baos.write(buffer, 0, length);}// 强制刷新,扫尾工作,主要是为了,让数据流在管道的传输工程中全部传输过去,防止丢失数据baos.flush();} catch (IOException e) {e.printStackTrace();}// 字节流转换字节数组byte[] data = baos.toByteArray();try {// 关闭读取流is.close();// 关闭写入流baos.close();} catch (IOException e) {e.printStackTrace();}return data;}/*** 获取本地图片的字节数** @param imgPath* @return*/public static String pathSize(String imgPath) {File file = new File(imgPath);FileInputStream fis;int fileLen = 0;try {fis = new FileInputStream(file);fileLen = fis.available();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return bytes2kb(fileLen);}/*** 将获取到的字节数转换为KB,MB模式** @param bytes* @return*/public static String bytes2kb(long bytes) {BigDecimal filesize = new BigDecimal(bytes);
//        BigDecimal megabyte = new BigDecimal(1024 * 1024);
//        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
//        if (returnValue > 1)
//            return (returnValue + "MB");
//        BigDecimal kilobyte = new BigDecimal(1024);
//        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP).floatValue();
//        return (returnValue + "KB");return filesize.toString();}public static String getImageFormat(String imagePath) throws IOException {// 字节数组byte[] data = null;String format = null;// 输入流InputStream is = null;// Http连接对象HttpURLConnection conn = null;ImageInputStream imageInputStream = null;try {// Url对象URL url = new URL(imagePath);// 打开连接conn = (HttpURLConnection) url.openConnection();// 打开读取 写入是setDoOutput
//	        conn.setDoOutput(true);conn.setDoInput(true);// 设置请求方式conn.setRequestMethod("GET");// 设置超时时间conn.setConnectTimeout(6000);// 得到访问的数据流is = conn.getInputStream();// 验证访问状态是否是200 正常if (conn.getResponseCode() == 200) {imageInputStream = ImageIO.createImageInputStream(is);ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();format = imageReader.getFormatName();} else {format = null;}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (is != null) {// 关闭流is.close();}if(imageInputStream != null){imageInputStream.close();}} catch (IOException e) {e.printStackTrace();}// 关闭连接conn.disconnect();}return format;}/*** 将inputStream转化为file* @param is* @param file 要输出的文件目录*/public static void inputStream2File(InputStream is, File file) throws IOException {OutputStream os = null;try {os = new FileOutputStream(file);int len = 0;byte[] buffer = new byte[8192];while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);}} finally {os.close();is.close();}}/*** 获取视频详情* @param file* @return*/public static VideoInfoVO getVideoInfo(String file) {VideoInfoVO videoInfoVO = new VideoInfoVO();FFmpegFrameGrabber grabber = null;try {grabber = FFmpegFrameGrabber.createDefault(file);// 启动 FFmpeggrabber.start();// 读取视频帧数videoInfoVO.setLengthInFrames(grabber.getLengthInVideoFrames());// 读取视频帧率videoInfoVO.setFrameRate(grabber.getVideoFrameRate());// 读取视频秒数videoInfoVO.setDuration(grabber.getLengthInTime() / 1000000.00);// 读取视频宽度videoInfoVO.setWidth(grabber.getImageWidth());// 读取视频高度videoInfoVO.setHeight(grabber.getImageHeight());videoInfoVO.setAudioChannel(grabber.getAudioChannels());videoInfoVO.setVideoCode(grabber.getVideoCodecName());videoInfoVO.setAudioCode(grabber.getAudioCodecName());// String md5 = MD5Util.getMD5ByInputStream(new FileInputStream(file));videoInfoVO.setSampleRate(grabber.getSampleRate());return videoInfoVO;} catch (Exception e) {e.printStackTrace();return null;} finally {try {if (grabber != null) {// 此处代码非常重要,如果没有,可能造成 FFmpeg 无法关闭grabber.stop();grabber.release();}} catch (FFmpegFrameGrabber.Exception e) {e.printStackTrace();}}}/*** 截取视频获得指定帧的图片(截取视频帧封面)** @param video   源视频文件*/public void getVideoPic(InputStream video) {FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);try {ff.start();// 截取中间帧图片(具体依实际情况而定)int i = 0;int length = ff.getLengthInFrames();
//            int middleFrame = length / 2;int middleFrame = 5;Frame frame = null;while (i < length) {frame = ff.grabFrame();if ((i > middleFrame) && (frame.image != null)) {break;}i++;}// 截取的帧图片Java2DFrameConverter converter = new Java2DFrameConverter();BufferedImage srcImage = converter.getBufferedImage(frame);int srcImageWidth = srcImage.getWidth();int srcImageHeight = srcImage.getHeight();BufferedImage image = new BufferedImage(srcImageWidth, srcImageHeight, BufferedImage.TYPE_INT_ARGB);Graphics2D g2d = image.createGraphics();g2d.setColor(Color.RED);g2d.fillRect(0, 0, srcImageWidth, srcImageHeight);g2d.setColor(Color.WHITE);g2d.drawString("Hello, World!", 50, 100);g2d.dispose();File file = new File("image.png");try {ImageIO.write(image, "png", file);} catch (IOException e) {e.printStackTrace();}ff.stop();} catch (java.lang.Exception e) {e.printStackTrace();System.out.println(e);}}/*** 获取文件大小* @param inputStream* @return*/public String getFileSize(InputStream inputStream){FileChannel fc = null;String size = "0";try {FileInputStream fis = convertToFileInputStream(inputStream);fc = fis.getChannel();BigDecimal fileSize = new BigDecimal(fc.size());size = String.valueOf(fileSize);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (null != fc) {try {fc.close();} catch (IOException e) {e.printStackTrace();}}}return size;}/*** inputStream转FileInputStream* @param inputStream* @return* @throws IOException*/public static FileInputStream convertToFileInputStream(InputStream inputStream) throws IOException {File tempFile = File.createTempFile("temp", ".tmp");tempFile.deleteOnExit();try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}return new FileInputStream(tempFile);}public void start(Stage primaryStage) {String videoPath = "C:\\Users\\DELL\\Desktop\\test.mp4";double position = 1200.0; // 播放位置(以秒为单位)// 创建媒体播放器Media media = new Media(new File(videoPath).toURI().toString());MediaPlayer mediaPlayer = new MediaPlayer(media);mediaPlayer.setOnReady(() -> {mediaPlayer.seek(mediaPlayer.getTotalDuration().multiply(position / mediaPlayer.getTotalDuration().toSeconds()));mediaPlayer.play();});mediaPlayer.setAutoPlay(true);// 创建媒体视图MediaView mediaView = new MediaView(mediaPlayer);// 创建控制按钮Button playButton = new Button("播放");Button pauseButton = new Button("暂停");Button stopButton = new Button("停止");// 播放按钮点击事件playButton.setOnAction(event -> mediaPlayer.play());// 暂停按钮点击事件pauseButton.setOnAction(event -> mediaPlayer.pause());// 停止按钮点击事件stopButton.setOnAction(event -> mediaPlayer.stop());// 创建音量调节滑块Slider volumeSlider = new Slider(0, 1, 0.5);volumeSlider.setPrefWidth(100);mediaPlayer.volumeProperty().bind(volumeSlider.valueProperty());// 创建按钮布局HBox buttonBox = new HBox(10);buttonBox.setAlignment(Pos.CENTER);buttonBox.getChildren().addAll(playButton, pauseButton, stopButton);// 创建根布局BorderPane root = new BorderPane();root.setCenter(mediaView);root.setBottom(volumeSlider);root.setTop(buttonBox);// 创建场景Scene scene = new Scene(root, 800, 600);// 设置舞台primaryStage.setScene(scene);primaryStage.setTitle("Video Player");primaryStage.show();}
}
实体VideoInfoVO类:
package com.example.mybatisdemo02.model;import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;@Getter
@Setter
public class VideoInfoVO {/*** 总帧数**/private int lengthInFrames;/*** 帧率**/private double frameRate;/*** 时长**/private double duration;/*** 视频编码*/private String videoCode;/*** 音频编码*/private String audioCode;private int width;private int height;private int audioChannel;private String md5;/*** 音频采样率*/private Integer sampleRate;private Double fileSize;public String toJson() {try {ObjectMapper objectMapper = new ObjectMapper();return objectMapper.writeValueAsString(this);} catch (Exception e) {return "";}}
}

调用:

public class Main {public static void main(String[] args) {VideoInfoVO videoInfoVO = FFmpegUtil.getVideoInfo("C:\\Users\\DELL\\Desktop\\test.mp4");int date = videoInfoVO.getLengthInFrames();double shichang = videoInfoVO.getDuration();System.out.println("帧数:"+date+"时长:"+shichang);}
}

结果如下图:

欢迎给个关注:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/587802.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

并发编程之线程池的底层原理的详细解析

线程池的底层原理 Executors源码&#xff1a; public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());} ​public static ExecutorServ…

Kaggle:收入分类

先看一下数据的统计信息 import pandas as pd # 加载数据&#xff08;保留原路径&#xff0c;但在实际应用中建议使用相对路径或环境变量&#xff09; data pd.read_csv(r"C:\Users\11794\Desktop\收入分类\training.csv", encodingutf-8, encoding_errorsrepl…

javaweb学习(day10-服务器渲染技术)

一、基本介绍 1.前言 目前主流的技术是 前后端分离 (比如: Spring Boot Vue/React)JSP 技术使用在逐渐减少&#xff0c;但使用少和没有使用是两个意思&#xff0c;一些老项目和中小公司还在使用 JSP&#xff0c;工作期间&#xff0c;你很有可能遇到 JSPJSP 使用在减少(但是现…

路径规划——搜索算法详解(七):D*lite算法详解与Matlab代码

&#xff01;&#xff01;&#xff01;注意&#xff01;&#xff01;&#xff01; 看本篇之前&#xff0c;一定要先看笔者上一篇的LPA*讲解&#xff0c;笔者统一了符号看起来过渡会更加好理解&#xff01; 到目前为止&#xff0c;我们学习了广度优先搜索Dijkstra算法、能够计…

OpenHarmony实战:轻量级系统之安全子系统移植

安全子系统提供网络设备连接、认证鉴权等功能&#xff0c;依赖mbedtls实现硬件随机数以及联网功能。 由于每个厂商芯片硬件与实现硬件随机数的方式不同&#xff0c;需要适配硬件随机数接口。 移植指导 OpenHarmony提供了mbedtls的开源三方库&#xff0c;路径为“//third_par…

Catcatcat【杂项 攻防世界】

知识点&#xff1a; strings 命令 打印文件中可以打印的字符&#xff0c;可以是任意文件grep flag 过滤出文件中的flag关键字rabbit加密 深入了解Rabbit加密技术&#xff1a;原理、实现与应用-CSDN博客对称加密算法需要密钥&#xff0c;也可不设置数据开头固定&#xff1a;U2F…

【Linux】在生产环境中,Linux系统排查常用命令

问题排查 文章目录 问题排查top命令CPU&#xff1a;vmstatprocscpu内存&#xff1a;free硬盘&#xff1a;df硬盘IO&#xff1a;iostat网络IO&#xff1a;ifstat 生产环境服务器变慢&#xff0c;诊断思路和性能评估 top命令 查看整机系统新能 使用top命令的话&#xff0c;重点…

55、美国德克萨斯大学奥斯汀分校、钱德拉家族电气与计算机工程系:通过迁移学习解决BCI个体差异性[不得不说,看技术还得是老美]

2024年2月5日跨被试最新文章&#xff1a; 德州州立大学奥斯汀分校研究团队最近的一项研究成果&#xff0c;通过非侵入式的脑机接口&#xff0c;可以让被试不需要任何校准就可以使用脑机接口设备&#xff0c;这意味着脑机接口具备了大规模被使用的潜力。 一般来说&#xff0c;…

【XR806开发板试用】简单点灯-- 基于SPI控制W2812矩阵幻彩动图和字幕显示系统

1.效果展示 1.gif 动图展示 2.字幕展示 2.软件开发流程 2.1 全志XR806 基本开发流程 使用指南 自己踩过的坑 必须app开头 鸿蒙hb 依赖python 环境。建议使用conda虚拟环境 下载开启硬件校验和烧录重启 2.2 W2812 简单介绍 不是科普文&#xff0c;自行百度 /*WS2812B T…

基于Pytorch+昇腾NPU部署baichuan2-7B大模型

一、模型介绍 Baichuan 2 是百川智能推出的新一代开源大语言模型&#xff0c;采用 2.6 万亿 Tokens 的高质量语料训练。Baichuan 2 在多个权威的中文、英文和多语言的通用、领域 benchmark 上取得同尺寸最佳的效果。 它基于 Transformer 结构&#xff0c;在大约1.2万亿 tokens…

etcdctl配置

下载etcdctl压缩文件 wget https://github.com/etcd-io/etcd/releases/download/v3.5.0/etcd-v3.5.0-linux-amd64.tar.gztar -xvf etcd-v3.5.0-linux-amd64.tar.gzsudo mv ./etcd-v3.5.0-linux-amd64/etcdctl /usr/local/bin/ chmod x /usr/local/bin/etcdctl 配置etcdctl 配…

Visual Studio安装下载进度为零已解决

因为在安装pytorch3d0.3.0时遇到问题&#xff0c;提示没有cl.exe&#xff0c;VS的C编译组件&#xff0c;可以添加组件也可以重装VS。查了下2019版比2022问题少&#xff0c;选择了安装2019版&#xff0c;下面是下载安装时遇到的问题记录&#xff0c;关于下载进度为零网上有三类解…