ffmpeg获取视频时长,宽高,等信息

 从其他地方找到的,做了一些修改,让信息获取更完整:

package com.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FfmpegUtil {
    private static final Pattern FORMAT_PATTERN = Pattern.compile("^\\s*([D ])([E ])\\s+([\\w,]+)\\s+.+$");
    private static final Pattern ENCODER_DECODER_PATTERN = Pattern.compile("^\\s*([D ])([E ])([AVS]).{3}\\s+(.+)$", 2);
    private static final Pattern PROGRESS_INFO_PATTERN = Pattern.compile("\\s*(\\w+)\\s*=\\s*(\\S+)\\s*", 2);
    private static final Pattern SIZE_PATTERN = Pattern.compile("(\\d+)x(\\d+)", 2);
    private static final Pattern FRAME_RATE_PATTERN = Pattern.compile("([\\d.]+)\\s+(?:fps|tb\\(r\\))", 2);
    private static final Pattern BIT_RATE_PATTERN = Pattern.compile("(\\d+)\\s+kb/s", 2);
    private static final Pattern SAMPLING_RATE_PATTERN = Pattern.compile("(\\d+)\\s+Hz", 2);
    private static final Pattern CHANNELS_PATTERN = Pattern.compile("(mono|stereo)", 2);
    private static final Pattern SUCCESS_PATTERN = Pattern.compile("^\\s*video\\:\\S+\\s+audio\\:\\S+\\s+global headers\\:\\S+.*$", 2);
    private static final Pattern p1 = Pattern.compile("^\\s*Input #0, (\\w+).+$\\s*", 2);
    private static final Pattern p2 = Pattern.compile("^\\s*Duration: (\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d).*$", 2);
    private static final Pattern p3 = Pattern.compile("^\\s*Stream #\\S+: ((?:Audio)|(?:Video)|(?:Data)): (.*)\\s*$", 2);

    //ffmepg文件 安装目录
    private static String FFMPEG_PATH = "D:\\\\ffmpeg\\\\bin\\\\ffmpeg";


    public static void main(String[] args) throws Exception {
        String file = "C:\\Users\\yy\\Desktop\\video\\33.mp4";
        MultimediaInfo info = getVideoInfo(file);
        // 时长信息
        long duration = info.getDuration();
        System.out.println("视频时长为:" + duration / 1000 + "秒");
        // 音频信息
        MultimediaInfo.AudioInfo audio = info.getAudio();
        if (audio != null) {
            int bitRate = audio.getBitRate();  // 比特率
            int channels = audio.getChannels();  // 声道
            String decoder = audio.getDecoder();  // 解码器
            int sRate = audio.getSamplingRate();  // 采样率
            System.out.println("解码器:" + decoder + ",声道:" + channels + ",比特率:" + bitRate + ",采样率:" + sRate);
        }
        // 视频信息
        MultimediaInfo.VideoInfo video = info.getVideo();
        if (video != null) {
            int bitRate2 = video.getBitRate();
            Float fRate = video.getFrameRate();  // 帧率
            int height = video.getHeight();  // 视频高度
            int width = video.getWidth();  // 视频宽度
            System.out.println("视频帧率:" + fRate + ",比特率:" + bitRate2 + ",视频高度:" + height + ",视频宽度:" + width);
        }
    }

    /**
     * 获取视频信息 支持http视频链接
     * @param file
     * @return
     */
    public static MultimediaInfo getVideoInfo(String file){
        try {
            String commond = FFMPEG_PATH+" -i "+file;
            List<String> stringBuilder = executeCommand4ResultList(commond);
            return parseMultimediaInfo(stringBuilder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 执行命令
     * @param command
     * @return
     * @throws IOException
     */
    private static List<String> executeCommand4ResultList(String command) throws IOException {
        String[] commandSplit = command.split(" ");
        List<String> lcommand = new ArrayList<>();
        for (int i = 0; i < commandSplit.length; i++) {
            if(commandSplit[i]!=null){
                lcommand.add(commandSplit[i]);
            }
        }
        ProcessBuilder processBuilder = new ProcessBuilder(lcommand);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        List<String> list = new ArrayList<>();

        try (InputStream is = process.getInputStream();
            BufferedReader bs = new BufferedReader(new InputStreamReader(is))) {

            String line = null;
            while ((line = bs.readLine()) != null) {
                list.add(line);
            }
            process.waitFor();
            if (process.exitValue() != 0) {
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            long end = System.currentTimeMillis();
        }
        return list;
    }

    /**
     * 处理媒体信息流
     * @param list
     * @return
     */
    public static MultimediaInfo parseMultimediaInfo(List<String> list){
        MultimediaInfo info = null;
        int step = 0;
        for (String line : list){
            if (line == null) {
                break;
            }
            String type;
            String specs;
            if (step == 0) {
                Matcher m = p1.matcher(line);
                if (m.matches()) {
                    specs = m.group(1);
                    info = new MultimediaInfo();
                    info.setFormat(specs);
                    ++step;
                }
            } else {
                Matcher m;
                if (step == 1) {
                    m = p2.matcher(line);
                    if (m.matches()) {
                        long hours = Long.parseLong(m.group(1));
                        long minutes = Long.parseLong(m.group(2));
                        long seconds = Long.parseLong(m.group(3));
                        long dec = Long.parseLong(m.group(4));
                        long duration = dec * 100L + seconds * 1000L + minutes * 60L * 1000L + hours * 60L * 60L * 1000L;
                        info.setDuration(duration);
                        ++step;
                    }
                } else if (step == 2) {
                    m = p3.matcher(line);
                    if (m.matches()) {
                        type = m.group(1);
                        specs = m.group(2);
                        StringTokenizer st;
                        String token;
                        Matcher m2;
                        int i;
                        boolean parsed;
                        int bitRate;
                        if ("Video".equalsIgnoreCase(type)) {
                            MultimediaInfo.VideoInfo video = new MultimediaInfo.VideoInfo();
                            st = new StringTokenizer(specs, ",");

                            for(i = 0; st.hasMoreTokens(); ++i) {
                                token = st.nextToken().trim();
                                if (i == 0) {
                                    video.setDecoder(token);
                                } else {
                                    parsed = false;
                                    m2 = SIZE_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        bitRate = Integer.parseInt(m2.group(1));
                                        int height = Integer.parseInt(m2.group(2));
                                        //video.setSize(new VideoSize(bitRate, height));
                                        video.setWidth(bitRate);
                                        video.setHeight(height);
                                        parsed = true;
                                    }

                                    m2 = FRAME_RATE_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        try {
                                            float frameRate = Float.parseFloat(m2.group(1));
                                            video.setFrameRate(frameRate);
                                        } catch (NumberFormatException var20) {
                                        }

                                        parsed = true;
                                    }

                                    m2 = BIT_RATE_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        bitRate = Integer.parseInt(m2.group(1));
                                        video.setBitRate(bitRate);
                                    }
                                }
                            }

                            info.setVideo(video);
                        } else if ("Audio".equalsIgnoreCase(type)) {
                            MultimediaInfo.AudioInfo audio = new MultimediaInfo.AudioInfo();
                            st = new StringTokenizer(specs, ",");

                            for(i = 0; st.hasMoreTokens(); ++i) {
                                token = st.nextToken().trim();
                                if (i == 0) {
                                    audio.setDecoder(token);
                                } else {
                                    parsed = false;
                                    m2 = SAMPLING_RATE_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        bitRate = Integer.parseInt(m2.group(1));
                                        audio.setSamplingRate(bitRate);
                                        parsed = true;
                                    }

                                    m2 = CHANNELS_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        String ms = m2.group(1);
                                        if ("mono".equalsIgnoreCase(ms)) {
                                            audio.setChannels(1);
                                        } else if ("stereo".equalsIgnoreCase(ms)) {
                                            audio.setChannels(2);
                                        }

                                        parsed = true;
                                    }

                                    m2 = BIT_RATE_PATTERN.matcher(token);
                                    if (!parsed && m2.find()) {
                                        bitRate = Integer.parseInt(m2.group(1));
                                        audio.setBitRate(bitRate);
                                    }
                                }
                            }
                            info.setAudio(audio);
                        }
                    }
                }
            }
        }

        if (info == null) {
            throw new RuntimeException("获取视频信息失败");
        } else {
            return info;
        }
    }
}
package com.util;

/**
 * 媒体信息类
 */
public class MultimediaInfo {
    //视频格式
    private String format = null;
    //视频时长 单位(毫秒)
    private long duration = -1L;
    //音频信息
    private AudioInfo audio = null;
    //视频信息
    private VideoInfo video = null;

    public MultimediaInfo() {
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public long getDuration() {
        return duration;
    }

    public void setDuration(long duration) {
        this.duration = duration;
    }

    public AudioInfo getAudio() {
        return audio;
    }

    public void setAudio(AudioInfo audio) {
        this.audio = audio;
    }

    public VideoInfo getVideo() {
        return video;
    }

    public void setVideo(VideoInfo video) {
        this.video = video;
    }

    @Override
    public String toString() {
        return "MultimediaInfo{" + "format='" + format + '\'' + ", duration=" + duration + ", audio=" + audio
            + ", video=" + video + '}';
    }

    public static class AudioInfo {
        //解码器
        private String decoder;
        //采样率
        private int samplingRate = -1;
        //声道
        private int channels = -1;
        //比特率
        private int bitRate = -1;

        public AudioInfo() {
        }

        public String getDecoder() {
            return decoder;
        }

        public void setDecoder(String decoder) {
            this.decoder = decoder;
        }

        public int getSamplingRate() {
            return samplingRate;
        }

        public void setSamplingRate(int samplingRate) {
            this.samplingRate = samplingRate;
        }

        public int getChannels() {
            return channels;
        }

        public void setChannels(int channels) {
            this.channels = channels;
        }

        public int getBitRate() {
            return bitRate;
        }

        public void setBitRate(int bitRate) {
            this.bitRate = bitRate;
        }

        @Override
        public String toString() {
            return "AudioInfo{" + "decoder='" + decoder + '\'' + ", samplingRate=" + samplingRate + ", channels="
                + channels + ", bitRate=" + bitRate + '}';
        }
    }

    public static class VideoInfo {
        //解码器
        private String decoder;
        //视频宽度
        private int width;
        //视频高度
        private int height;
        //比特率
        private int bitRate = -1;
        //帧率
        private float frameRate = -1.0F;

        public VideoInfo() {
        }

        public String getDecoder() {
            return decoder;
        }

        public void setDecoder(String decoder) {
            this.decoder = decoder;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getBitRate() {
            return bitRate;
        }

        public void setBitRate(int bitRate) {
            this.bitRate = bitRate;
        }

        public float getFrameRate() {
            return frameRate;
        }

        public void setFrameRate(float frameRate) {
            this.frameRate = frameRate;
        }

        @Override
        public String toString() {
            return "VideoInfo{" + "decoder='" + decoder + '\'' + ", width=" + width + ", height=" + height
                + ", bitRate=" + bitRate + ", frameRate=" + frameRate + '}';
        }
    }
}

 

FFmpeg中,获取视频时长可以通过AVFormatContext中的duration字段来实现,该字段表示音视频文件的总时长,单位是微秒(us)。如果duration为AV_NOPTS_VALUE,则表示无法获取时长。 具体实现代码如下: ```c AVFormatContext *fmt_ctx = NULL; if (avformat_open_input(&fmt_ctx, filename, NULL, NULL) != 0) { printf("Failed to open file '%s'\n", filename); return -1; } if (avformat_find_stream_info(fmt_ctx, NULL) < 0) { printf("Failed to retrieve input stream information\n"); return -1; } int64_t duration = fmt_ctx->duration; if (duration != AV_NOPTS_VALUE) { int hours, mins, secs, us; secs = duration / AV_TIME_BASE; us = duration % AV_TIME_BASE; mins = secs / 60; secs %= 60; hours = mins / 60; mins %= 60; printf("Duration: %02d:%02d:%02d.%02d\n", hours, mins, secs, (100 * us) / AV_TIME_BASE); } else { printf("Duration: N/A\n"); } avformat_close_input(&fmt_ctx); ``` 在这个例子中,我们首先使用avformat_open_input函数打开音视频文件,然后通过avformat_find_stream_info函数获取视频文件的流信息,接着获取AVFormatContext的duration字段,如果duration不为AV_NOPTS_VALUE,则表示获取到了时长,我们将其转换为时分秒的格式进行输出。最后,我们需要调用avformat_close_input函数关闭文件并释放资源。 需要注意的是,由于duration字段的单位是微秒,因此我们需要将其转换为秒,进而转换为时分秒格式。另外,如果获取时长失败,则duration的值将为AV_NOPTS_VALUE,我们需要做特殊处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值