0


Golang 将视频按照时间维度剪切 | Golang工具

前言

本文提供将视频按照时间维度进行剪切的工具方法,一如既往的实用主义。

主要也是学习一下golang使用ffmpeg工具的方式。

环境依赖

ffmpeg环境安装,可以参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客

本文主要使用到的不是ffmpeg,而是ffprobe也在上面这篇文章中的zip包中。

​​

golang主要依赖库

github.com/u2takey/ffmpeg-go

代码

不废话,上代码。下面为功能实现的主要代码。

package main

import (
    "csdn/utils"
    "fmt"
    "github.com/gofrs/uuid"
    "github.com/google/logger"
    ffmpeg "github.com/u2takey/ffmpeg-go"
    "path/filepath"
    "strings"
)

func in(target string, str_array []string) bool {
    for _, element := range str_array {
        if target == element {
            return true
        }
    }
    return false
}

//剪切视频
func CutVideo(inputVideoPath, outputDir, startTime string, duration int) string {
    _formatArr := []string{"mp4", "flv"}
    _, _file := filepath.Split(inputVideoPath)
    _tmps := strings.Split(_file, ".")
    _ext := _tmps[len(_tmps)-1]
    if !in(_ext, _formatArr) {
        logger.Fatal("格式不支持")
    }
    _name, err := uuid.NewV4()
    if err != nil {
        logger.Fatal(err)
    }
    _resultVideoPath := filepath.Join(outputDir, fmt.Sprintf("%s.%s", _name.String(), _ext))
    err = ffmpeg.Input(inputVideoPath).
        Output(_resultVideoPath, ffmpeg.KwArgs{"ss": startTime, "t": duration, "c:v": "copy", "c:a": "copy"}).
        OverWriteOutput().ErrorToStdOut().Run()
    if err != nil {
        logger.Fatal(err)
    }
    return _resultVideoPath
}

func main() {
    logutil.Init(true, false, "1.log")
    defer logutil.Close()
    _result := CutVideo("E:\\360MoveData\\Users\\huyi\\Desktop\\3333333.mp4", "E:\\360MoveData\\Users\\huyi\\Desktop", "0:10", 5)
    fmt.Println(_result)
}

日志工具代码如下,非必要。

package logutil

import (
    "github.com/google/logger"
    "os"
)

var pLogger *logger.Logger

// Init init logger
func Init(verbose, systemLog bool, logPath string) {
    file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)
    if err != nil {
        logger.Fatalf("logger Init: open log file(%v) error(%v)", logPath, err)
    }
    pLogger = logger.Init("FFmpegDemoLogger", verbose, systemLog, file)
}

// Close close logger
func Close() {
    pLogger.Close()
}

代码说明

1、CutVideo方法参数分别为,输入视频地址、输出目录地址、剪切起始时间点、剪切持续时间。

2、起始时间的格式要注意,给了几个格式样式:0:01、10:11,前面为分钟后面为秒。

3、做了简单的视频格式校验,如需添加,可以自己看着来。

4、最终视频名使用uuid避免重复。

5、剪切的视频时长不能超过视频时间。

验证一下

准备的视频信息。

​​

执行结果

2022/12/27 14:10:54 compiled command: ffmpeg -i E:\360MoveData\Users\huyi\Desktop\3333333.mp4 -c:a copy -c:v copy -ss 0:10 -t 5 E:\360MoveData\Users\huyi\Desktop\eab5ec1a-acc2-4600-
b720-93b5ca5f6464.mp4 -y
ffmpeg version n4.3.1-20-g8a2acdc6da Copyright (c) 2000-2020 the FFmpeg developers
built with gcc 9.3-win32 (GCC) 20200320
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --ena
ble-version3 --disable-debug --enable-iconv --enable-zlib --enable-libxml2 --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvmaf -
-disable-vulkan --enable-libvorbis --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-ffnvcodec --enable-cuda-llvm --disable-libglslang --enable-libass --enab
le-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-
libopenjpeg --enable-librav1e --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libtwolame --enable-libvidstab --enable-libx264 --enable-libx265 --enable-lib
xvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-libs=-lgomp
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
libpostproc 55. 7.100 / 55. 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\eab5ec1a-acc2-4600-b720-93b5ca5f6464.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= 6607kB time=00:00:04.97 bitrate=10875.7kbits/s speed= 313x
video:6507kB audio:95kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.082792%
E:\360MoveData\Users\huyi\Desktop\eab5ec1a-acc2-4600-b720-93b5ca5f6464.mp4

结果视频信息

总结

没啥好总结的,注意视频时长。

分享:

    人生最重要的不是以你的所得投资,任何人都可以这样做。真正重要的是如何从损失中获利。这才需要智慧,才能显示出人的上智下愚。——《人性的弱点》

如果本文对你有帮助的话,点个赞吧,谢谢!

标签: golang 音视频 ffmpeg

本文转载自: https://blog.csdn.net/zhiweihongyan1/article/details/128455131
版权归原作者 剑客阿良_ALiang 所有, 如有侵权,请联系我们删除。

“Golang 将视频按照时间维度剪切 | Golang工具”的评论:

还没有评论