Java获取视频时长和封面截图

 更新时间:2025年03月03日 09:56:46   作者:狼狂人  
这篇文章主要为大家详细介绍了如何使用Java获取视频时长和封面截图功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

java视频时长的计算以及视频封面图截取

本人使用的maven进行下载对应的jar包,其中代码适用window环境和linux环境,亲自测过,没问题。

maven需要用到的groupId和artifactId以及版本,如下所示:

<dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacpp</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>opencv-platform</artifactId>
            <version>3.4.1-1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>ffmpeg-platform</artifactId>
            <version>3.4.2-1.4.1</version>
        </dependency>

java代码

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

/**
 * 视频工具
 * @author 
 *
 */
public class VideoUtil {
    /**
     * 获取指定视频的帧并保存为图片至指定目录
     * @param file  源视频文件
     * @param framefile  截取帧的图片存放路径
     * @throws Exception
     */
    public static void fetchPic(File file, String framefile) throws Exception{
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file); 
        ff.start();
        int lenght = ff.getLengthInFrames();

        File targetFile = new File(framefile);
        int i = 0;
        Frame frame = null;
        while (i < lenght) {
            // 过滤前5帧,避免出现全黑的图片,依自己情况而定
            frame = ff.grabFrame();
            if ((i > 5) && (frame.image != null)) {
                break;
            }
            i++;
        }      

        String imgSuffix = "jpg";
        if(framefile.indexOf('.') != -1){
            String[] arr = framefile.split("\\.");
            if(arr.length>=2){
                imgSuffix = arr[1];
            }
        }

        Java2DFrameConverter converter =new Java2DFrameConverter();
        BufferedImage srcBi =converter.getBufferedImage(frame);
        int owidth = srcBi.getWidth();
        int oheight = srcBi.getHeight();
        // 对截取的帧进行等比例缩放
        int width = 800;
        int height = (int) (((double) width / owidth) * oheight);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        bi.getGraphics().drawImage(srcBi.getScaledInstance(width, height, Image.SCALE_SMOOTH),0, 0, null);
        try {
            ImageIO.write(bi, imgSuffix, targetFile);
        }catch (Exception e) {
            e.printStackTrace();
        }      
        ff.stop();
    }

    /**
     * 获取视频时长,单位为秒
     * @param file
     * @return 时长(s)
     */
    public static Long getVideoTime(File file){
        Long times = 0L;
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file); 
            ff.start();
            times = ff.getLengthInTime()/(1000*1000);
            ff.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }
}

以上就是java获取视频的时长,以及视频获取其中封面截图。

除了上文的方法,小编还为大家整理了其他java获取视频时长(实测可行)的方法,希望对大家有所帮助

下面是完整代码

pom.xml

 <!-- mp3文件支持(如语音时长)-->
    <dependency>
      <groupId>org</groupId>
      <artifactId>jaudiotagger</artifactId>
      <version>2.0.1</version>
    </dependency>

    <!-- mp4文件支持(如语音时长)-->
    <dependency>
      <groupId>com.googlecode.mp4parser</groupId>
      <artifactId>isoparser</artifactId>
      <version>1.1.22</version>
    </dependency>

单元测试

package com.opensourceteams.modules.java.util.video;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.*;

public class VideoUtilTest {

    @Test
    public void getDuration() throws IOException {
        String path = "/Users/liuwen/Downloads/temp/语音测试文件/xiaoshizi.mp3" ;
      /*path 为本地地址 */

        long result = VideoUtil.getDuration(path);
        System.out.println(result);
    }

}

工具类

package com.opensourceteams.modules.java.util.video;



import com.coremedia.iso.IsoFile;

import java.io.IOException;


public class VideoUtil {



    /**
     * 获取视频文件的播放长度(mp4、mov格式)
     * @param videoPath
     * @return 单位为毫秒
     */
    public static long getMp4Duration(String videoPath) throws IOException {
        IsoFile isoFile = new IsoFile(videoPath);
        long lengthInSeconds =
                isoFile.getMovieBox().getMovieHeaderBox().getDuration() /
                isoFile.getMovieBox().getMovieHeaderBox().getTimescale();
        return lengthInSeconds;
    }


    /**
     * 得到语音或视频文件时长,单位秒
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath) throws IOException {
        String format = getVideoFormat(filePath);
        long result = 0;
        if("wav".equals(format)){
            result = AudioUtil.getDuration(filePath).intValue();
        }else if("mp3".equals(format)){
            result = AudioUtil.getMp3Duration(filePath).intValue();
        }else if("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mov".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mp4".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }

    /**
     * 得到语音或视频文件时长,单位秒
     * @param filePath
     * @return
     * @throws IOException
     */
    public static long getDuration(String filePath,String format) throws IOException {
        long result = 0;
        if("wav".equals(format)){
            result = AudioUtil.getDuration(filePath).intValue();
        }else if("mp3".equals(format)){
            result = AudioUtil.getMp3Duration(filePath).intValue();
        }else if("m4a".equals(format)) {
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mov".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }else if("mp4".equals(format)){
            result = VideoUtil.getMp4Duration(filePath);
        }

        return result;
    }


    /**
     * 得到文件格式
     * @param path
     * @return
     */
    public static String getVideoFormat(String path){
        return  path.toLowerCase().substring(path.toLowerCase().lastIndexOf(".") + 1);
    }


}
package com.opensourceteams.modules.java.util.video;

import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;


import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.File;

public class AudioUtil {



    /**
     * 获取语音文件播放时长(秒) 支持wav 格式
     * @param filePath
     * @return
     */
    public static Float getDuration(String filePath){
        try{

            File destFile = new File(filePath);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(destFile);
            AudioFormat format = audioInputStream.getFormat();
            long audioFileLength = destFile.length();
            int frameSize = format.getFrameSize();
            float frameRate = format.getFrameRate();
            float durationInSeconds = (audioFileLength / (frameSize * frameRate));
            return durationInSeconds;

        }catch (Exception e){
            e.printStackTrace();
            return 0f;
        }

    }

    /**
     * 获取mp3语音文件播放时长(秒) mp3
     * @param filePath
     * @return
     */
    public static Float getMp3Duration(String filePath){

        try {
            File mp3File = new File(filePath);
            MP3File f = (MP3File) AudioFileIO.read(mp3File);
            MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
            return Float.parseFloat(audioHeader.getTrackLength()+"");
        } catch(Exception e) {
            e.printStackTrace();
            return 0f;
        }
    }


    /**
     * 获取mp3语音文件播放时长(秒)
     * @param mp3File
     * @return
     */
    public static Float getMp3Duration(File mp3File){

        try {
            //File mp3File = new File(filePath);
            MP3File f = (MP3File) AudioFileIO.read(mp3File);
            MP3AudioHeader audioHeader = (MP3AudioHeader)f.getAudioHeader();
            return Float.parseFloat(audioHeader.getTrackLength()+"");
        } catch(Exception e) {
            e.printStackTrace();
            return 0f;
        }
    }


    /**
     * 得到pcm文件的毫秒数
     *
     * pcm文件音频时长计算
     * 同图像bmp文件一样,pcm文件保存的是未压缩的音频信息。 16bits 编码是指,每次采样的音频信息用2个字节保存。可以对比下bmp文件用分别用2个字节保存RGB颜色的信息。 16000采样率 是指 1秒钟采样 16000次。常见的音频是44100HZ,即一秒采样44100次。 单声道: 只有一个声道。
     *
     * 根据这些信息,我们可以计算: 1秒的16000采样率音频文件大小是 2*16000 = 32000字节 ,约为32K 1秒的8000采样率音频文件大小是 2*8000 = 16000字节 ,约为 16K
     *
     * 如果已知录音时长,可以根据文件的大小计算采样率是否正常。
     * @param filePath
     * @return
     */
    public static long getPCMDurationMilliSecond(String filePath) {
        File file = new File(filePath);

        //得到多少秒
        long second = file.length() / 32000 ;

        long milliSecond = Math.round((file.length() % 32000)   / 32000.0  * 1000 ) ;

        return second * 1000 + milliSecond;
    }
}

因为我们是根据在线url获取视频时长的

还需要再添加一步: 本地临时存储文件

 public void getDuration() throws IOException {
        File file = getFileByUrl("https://video-ecook.oss-cn-hangzhou.aliyuncs.com/76bd353630be47f0b5447ec06201ee56.mp4");
        String path = file.getCanonicalPath(); ;
        System.out.println(path);

        long result = VideoUtil.getDuration(path);
        System.out.println(result + "s");
    }
 public static File getFileByUrl(String url) throws IOException {
        File tmpFile = File.createTempFile("temp", ".mp4");//创建临时文件
        Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
        return tmpFile;
    }

到此这篇关于Java获取视频时长和封面截图的文章就介绍到这了,更多相关Java获取视频时长和封面内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 从Java的jar文件中读取数据的方法

    从Java的jar文件中读取数据的方法

    这篇文章主要介绍了从Java的jar文件中读取数据的方法,实例分析了java档案文件的相关操作技巧,需要的朋友可以参考下
    2015-06-06
  • 配置javaw.exe双击运行jar包方式

    配置javaw.exe双击运行jar包方式

    这篇文章主要介绍了配置javaw.exe双击运行jar包方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • 程序员最喜欢的ThreadLocal使用姿势

    程序员最喜欢的ThreadLocal使用姿势

    ThreadLocal并不是一个Thread,而是Thread的局部变量,也许把它命名为ThreadLocalVariable更容易让人理解一些,下面这篇文章主要给大家介绍了程序员最喜欢的ThreadLocal使用姿势,需要的朋友可以参考下
    2022-02-02
  • Springboot公共字段填充及ThreadLocal模块改进方案

    Springboot公共字段填充及ThreadLocal模块改进方案

    这篇文章主要为大家介绍了Springboot公共字段填充及ThreadLocal模块改进方案详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11
  • java内部类使用总结

    java内部类使用总结

    本文主要介绍了java内部类使用总结。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • springboot 加载本地jar到maven的实现方法

    springboot 加载本地jar到maven的实现方法

    如何在SpringBoot项目中加载本地jar到Maven本地仓库,使用Maven的install-file目标来实现,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2025-01-01
  • IDEA部署jeesite3完美运行教程详解

    IDEA部署jeesite3完美运行教程详解

    这篇文章主要介绍了IDEA部署jeesite3完美运行教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Netty如何自定义编码解码器

    Netty如何自定义编码解码器

    Netty自定义编码解码器:InboundHandler处理入栈数据,OutboundHandler处理出栈数据,解码器继承ByteToMessageDecoder,编码器继承MessageToByteEncoder,ReplayingDecoder简化了解码逻辑,但可能因异常重试导致性能下降
    2025-03-03
  • SpringBoot使用@Slf4j注解实现日志输出的示例代码

    SpringBoot使用@Slf4j注解实现日志输出的示例代码

    @Slf4j 是 Lombok 库中的一个注解,它极大地简化了日志记录的代码,通过使用这个注解,Lombok 会自动在你的类中注入一个静态的日志对象,本文给大家介绍了SpringBoot使用@Slf4j注解实现日志输出的方法,需要的朋友可以参考下
    2024-10-10
  • SpringMVC之RequestContextHolder详细解析

    SpringMVC之RequestContextHolder详细解析

    这篇文章主要介绍了SpringMVC之RequestContextHolder详细解析,正常来说在service层是没有request的,然而直接从controlller传过来的话解决方法太粗暴,后来发现了SpringMVC提供的RequestContextHolder,需要的朋友可以参考下
    2023-11-11

最新评论