Java implements video time dimension cutting | Java tool class

Table of contents

foreword

Maven dependencies

the code

Summarize


foreword

This article provides a Java tool class for cutting videos according to the time dimension, which is as pragmatic as ever.

Maven dependencies

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
        <dependency>
            <groupId>org.bytedeco</groupId>
            <artifactId>javacv-platform</artifactId>
            <version>1.5.5</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.2</version>
        </dependency>

the code

No nonsense, on the code.

package ai.guiji.csdn.tools;

import cn.hutool.core.util.IdUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.bytedeco.javacpp.Loader;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/** @Author 剑客阿良_ALiang @Date 2022/12/27 9:23 @Description: 视频剪切工具 */
public class CutVideoUtils {
  /**
   * 剪切视频
   *
   * @param inputVideoPath 输入视频地址
   * @param outputDir 输出目录
   * @param startTime 起始时间,格式:0:01、10:08
   * @param duration 持续时间,单位为:秒
   * @return 图片地址
   * @throws Exception 异常
   */
  public static String cut(
      String inputVideoPath, String outputDir, String startTime, Integer duration)
      throws Exception {
    List<String> paths = Splitter.on(".").splitToList(inputVideoPath);
    String ext = paths.get(paths.size() - 1);
    if (!Arrays.asList("mp4", "flv").contains(ext)) {
      throw new Exception("format error");
    }
    String resultPath =
        Joiner.on(File.separator).join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + ext));
    String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
    ProcessBuilder builder =
        new ProcessBuilder(
            ffmpeg,
            "-ss",
            startTime,
            "-i",
            inputVideoPath,
            "-t",
            String.valueOf(duration),
            "-c:v",
            "copy",
            "-c:a",
            "copy",
            "-y",
            resultPath);
    builder.inheritIO().start().waitFor();
    return resultPath;
  }

  public static void main(String[] args) throws Exception {
    System.out.println(
        cut(
            "E:\\360MoveData\\Users\\huyi\\Desktop\\3333333.mp4",
            "E:\\360MoveData\\Users\\huyi\\Desktop\\",
            "0:10",
            5));
  }
}

Code description:

1. The parameters of the cut method are the input video path, the output temporary directory, the cut start point, and the cut duration.

2. Pay attention to the format of the start time. Several formats are given: 0:01, 10:11, with minutes in front and seconds in the back.

3. The format of the file suffix has been verified, and you can adjust it according to your needs.

4. The cutting time should not exceed the length of the video.

verify

The prepared video information is as follows

 

Results of the

ffmpeg version 4.3.2 Copyright (c) 2000-2021 the FFmpeg developers
  built with gcc 10.2.0 (Rev5, Built by MSYS2 project)
  configuration: --prefix=.. --disable-iconv --disable-opencl --disable-sdl2 --disable-bzlib --disable-lzma --disable-linux-perf --enable-shared --enable-version3 --enable-runtime-cpudetect --enable-zlib --enable-libmp3lame --enable-libspeex --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvo-amrwbenc --enable-openssl --enable-libopenh264 --enable-libvpx --enable-libfreetype --enable-libopus --enable-cuda --enable-cuvid --enable-nvenc --enable-libmfx --enable-w32threads --enable-indev=dshow --target-os=mingw32 --cc='gcc -m64' --extra-cflags=-I../include/ --extra-ldflags=-L../lib/ --extra-libs='-static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lgcc_eh -lWs2_32 -lcrypt32 -lpthread -lz -lm -Wl,-Bdynamic -lole32 -luuid'
  libavutil      56. 51.100 / 56. 51.100
  libavcodec     58. 91.100 / 58. 91.100
  libavformat    58. 45.100 / 58. 45.100
  libavdevice    58. 10.100 / 58. 10.100
  libavfilter     7. 85.100 /  7. 85.100
  libswscale      5.  7.100 /  5.  7.100
  libswresample   3.  7.100 /  3.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'E:\360MoveData\Users\huyi\Desktop\3333333.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    creation_time   : 2022-09-08T12:04:43.000000Z
    Hw              : 1
                    : 
    bitRate         : 16000000
                    : 
    com.apple.quicktime.artwork: {"data":{"edittime":22,"infoStickerId":"","musicId":"","os":"windows","product":"lv","stickerId":"","videoEffectId":"","videoId":"245ba6f1-f2ab-4d70-bc77-c70ea30c171a","videoParams":{"be":0,"ef":0,"ft":0,"ma":0,"me":0,"mu":0,"re":0,"sp":0,"st":0,"te":0,"t
    maxrate         : 16000000
                    : 
    te_is_reencode  : 1
                    : 
    encoder         : Lavf58.76.100
  Duration: 00:00:26.91, start: 0.000000, bitrate: 11898 kb/s
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080 [SAR 1:1 DAR 16:9], 11741 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 156 kb/s (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : SoundHandler
Output #0, mp4, to 'E:\360MoveData\Users\huyi\Desktop\\51afc6ecc1824343a779ac66fc43668c.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    te_is_reencode  : 1
                    : 
    Hw              : 1
                    : 
    bitRate         : 16000000
                    : 
    com.apple.quicktime.artwork: {"data":{"edittime":22,"infoStickerId":"","musicId":"","os":"windows","product":"lv","stickerId":"","videoEffectId":"","videoId":"245ba6f1-f2ab-4d70-bc77-c70ea30c171a","videoParams":{"be":0,"ef":0,"ft":0,"ma":0,"me":0,"mu":0,"re":0,"sp":0,"st":0,"te":0,"t
    maxrate         : 16000000
                    : 
    encoder         : Lavf58.45.100
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080 [SAR 1:1 DAR 16:9], q=2-31, 11741 kb/s, 30 fps, 30 tbr, 15360 tbn, 15360 tbc (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : VideoHandler
    Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 156 kb/s (default)
    Metadata:
      creation_time   : 2022-09-08T12:04:43.000000Z
      handler_name    : SoundHandler
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (copy)
Press [q] to stop, [?] for help
frame=  150 fps=0.0 q=-1.0 Lsize=    6608kB time=00:00:04.97 bitrate=10876.3kbits/s speed= 625x    
video:6507kB audio:95kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.082907%
E:\360MoveData\Users\huyi\Desktop\\51afc6ecc1824343a779ac66fc43668c.mp4

Process finished with exit code 0
 

The resulting video information is as follows

OK, no problem!

Summarize

There is nothing to summarize, pay attention to the time interval.

share

        One day one learns that envy is the most useless thing, and that imitating others is tantamount to suicide. ——"The Weakness of Human Nature"

If this article is helpful to you, please like it , thank you! !

Guess you like

Origin blog.csdn.net/zhiweihongyan1/article/details/128451979