最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java獲取視頻時(shí)長和封面截圖

 更新時(shí)間:2025年03月03日 09:56:46   作者:狼狂人  
這篇文章主要為大家詳細(xì)介紹了如何使用Java獲取視頻時(shí)長和封面截圖功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

java視頻時(shí)長的計(jì)算以及視頻封面圖截取

本人使用的maven進(jìn)行下載對應(yīng)的jar包,其中代碼適用window環(huán)境和linux環(huán)境,親自測過,沒問題。

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幀,避免出現(xiàn)全黑的圖片,依自己情況而定
            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();
        // 對截取的幀進(jìn)行等比例縮放
        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();
    }

    /**
     * 獲取視頻時(shí)長,單位為秒
     * @param file
     * @return 時(shí)長(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獲取視頻的時(shí)長,以及視頻獲取其中封面截圖。

除了上文的方法,小編還為大家整理了其他java獲取視頻時(shí)長(實(shí)測可行)的方法,希望對大家有所幫助

下面是完整代碼

pom.xml

 <!-- mp3文件支持(如語音時(shí)長)-->
    <dependency>
      <groupId>org</groupId>
      <artifactId>jaudiotagger</artifactId>
      <version>2.0.1</version>
    </dependency>

    <!-- mp4文件支持(如語音時(shí)長)-->
    <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;
    }


    /**
     * 得到語音或視頻文件時(shí)長,單位秒
     * @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;
    }

    /**
     * 得到語音或視頻文件時(shí)長,單位秒
     * @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 {



    /**
     * 獲取語音文件播放時(shí)長(秒) 支持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語音文件播放時(shí)長(秒) 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語音文件播放時(shí)長(秒)
     * @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文件的毫秒數(shù)
     *
     * pcm文件音頻時(shí)長計(jì)算
     * 同圖像bmp文件一樣,pcm文件保存的是未壓縮的音頻信息。 16bits 編碼是指,每次采樣的音頻信息用2個(gè)字節(jié)保存??梢詫Ρ认耣mp文件用分別用2個(gè)字節(jié)保存RGB顏色的信息。 16000采樣率 是指 1秒鐘采樣 16000次。常見的音頻是44100HZ,即一秒采樣44100次。 單聲道: 只有一個(gè)聲道。
     *
     * 根據(jù)這些信息,我們可以計(jì)算: 1秒的16000采樣率音頻文件大小是 2*16000 = 32000字節(jié) ,約為32K 1秒的8000采樣率音頻文件大小是 2*8000 = 16000字節(jié) ,約為 16K
     *
     * 如果已知錄音時(shí)長,可以根據(jù)文件的大小計(jì)算采樣率是否正常。
     * @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;
    }
}

因?yàn)槲覀兪歉鶕?jù)在線url獲取視頻時(shí)長的

還需要再添加一步: 本地臨時(shí)存儲文件

 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");//創(chuàng)建臨時(shí)文件
        Image2Binary.toBDFile(url, tmpFile.getCanonicalPath());
        return tmpFile;
    }

到此這篇關(guān)于Java獲取視頻時(shí)長和封面截圖的文章就介紹到這了,更多相關(guān)Java獲取視頻時(shí)長和封面內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java中如何判斷對象是否是垃圾

    java中如何判斷對象是否是垃圾

    這篇文章主要介紹了java中如何判斷對象是否是垃圾,Java有兩種算法判斷對象是否是垃圾:引用計(jì)數(shù)算法和可達(dá)性分析算法,需要的朋友可以參考下
    2023-04-04
  • Java ArrayList深入源碼層分析

    Java ArrayList深入源碼層分析

    Java中容器對象主要用來存儲其他對象,根據(jù)實(shí)現(xiàn)原理不同,主要有3類常用的容器對象:ArrayList使用數(shù)組結(jié)構(gòu)存儲容器中的元素、LinkedList使用鏈表結(jié)構(gòu)存儲容器中的元素
    2023-01-01
  • Springboot整合Swagger3全注解配置(springdoc-openapi-ui)

    Springboot整合Swagger3全注解配置(springdoc-openapi-ui)

    本文主要介紹了Springboot整合Swagger3全注解配置(springdoc-openapi-ui),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • springboot?vue接口測試前后端實(shí)現(xiàn)模塊樹列表功能

    springboot?vue接口測試前后端實(shí)現(xiàn)模塊樹列表功能

    這篇文章主要為大家介紹了springboot?vue接口測試前后端實(shí)現(xiàn)模塊樹列表功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 解讀JSONArray刪除元素的兩種方式

    解讀JSONArray刪除元素的兩種方式

    這篇文章主要介紹了解讀JSONArray刪除元素的兩種方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • springboot使用小工具之Lombok、devtools、Spring Initailizr詳解

    springboot使用小工具之Lombok、devtools、Spring Initailizr詳解

    這篇文章主要介紹了springboot使用小工具之Lombok、devtools、Spring Initailizr詳解,Lombok可以代替手寫get、set、構(gòu)造方法等,需要idea裝插件lombok,本文通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-10-10
  • swing組件JScrollPane滾動條實(shí)例代碼

    swing組件JScrollPane滾動條實(shí)例代碼

    這篇文章主要介紹了swing組件JScrollPane滾動條實(shí)例代碼,分享了兩個(gè)相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • Java之String字符串在JVM中的存儲及其內(nèi)存地址的問題

    Java之String字符串在JVM中的存儲及其內(nèi)存地址的問題

    這篇文章主要介紹了Java之String字符串在JVM中的存儲及其內(nèi)存地址的問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式

    Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式

    本文主要介紹了Java延時(shí)執(zhí)行的三種實(shí)現(xiàn)方式,主要包括了Thread.sleep()方法,.sleep()使用Timer類或使用ScheduledExecutorService接口,感興趣的可以了解一下
    2023-12-12
  • idea啟動報(bào)錯(cuò):Command line is too long問題

    idea啟動報(bào)錯(cuò):Command line is too long問題

    在使用IDEA時(shí),若遇到"Commandlineistoolong"錯(cuò)誤,通常是因?yàn)槊钚虚L度超限,這是因?yàn)镮DEA通過命令行或文件將classpath傳遞至JVM,操作系統(tǒng)對命令行長度有限制,解決方法是切換至動態(tài)類路徑,通過修改項(xiàng)目的workspace.xml文件
    2024-09-09

最新評論

遂昌县| 海林市| 亚东县| 昭觉县| 武功县| 昭觉县| 罗山县| 湖口县| 和顺县| 类乌齐县| 和顺县| 青海省| 青海省| 皮山县| 儋州市| 临海市| 同仁县| 辽中县| 宁国市| 郯城县| 巍山| 通许县| 绥阳县| 兖州市| 贡山| 大厂| 泗阳县| 泗水县| 崇明县| 九龙坡区| 台东市| 额济纳旗| 宣恩县| 都昌县| 沙田区| 白沙| 巫溪县| 泽州县| 布拖县| 迁西县| 东明县|