一、通过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"); //提取视频文件的fps
                        fps = 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

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐