SoFunction
Updated on 2024-12-13

Python implementation to cut video by time dimension

preamble

This article provides the tool method to cut the video in the time dimension, as always pragmatic.

environmental dependency

ffmpeg environment installation, you can refer to the end of the article to add content

This article mainly uses not ffmpeg, but ffprobe.

ffmpy installation:

pip install ffmpy -i /simple

coding

No bullshit, on to the code.

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@author : Kenshi Aryan_ALiang
@file : cut_video.py
@ide : PyCharm
@time : 2022-12-27 10:22:48
"""
 
import os
import uuid
from ffmpy import FFmpeg
 
 
# Video cropping
# start_time format sample: 0:00,10:18
def cut_video_by_time(video_path: str, output_dir: str, start_time: str, duration: int):
    ext = (video_path).strip().split('.')[-1]
    if ext not in ['mp4', 'avi', 'flv']:
        raise Exception('format error')
    result = (output_dir, '{}.{}'.format(uuid.uuid1().hex, ext))
    ff = FFmpeg(inputs={video_path: None},
                outputs={
                    result: '-ss {} -t {} -c:v copy -c:a copy -y'.format(start_time, duration)})
    print()
    ()
    return result
 
 
if __name__ == '__main__':
    print(cut_video_by_time(r'E:\360MoveData\Users\huyi\Desktop\3333333.mp4', r'E:\360MoveData\Users\huyi\Desktop',
                            '0:10', 5))

Code Description

1, cut_video_by_time method parameters are, respectively, the input video address, the output directory address, cut start time point, cut duration.

2, the format of the starting time to pay attention to, give a few format styles: 0:01, 10:11, in front of the minutes behind the seconds.

3, made a simple video format verification, such as the need to add, you can watch yourself.

4. Use uuid for the final video name to avoid duplication.

5. The length of the cut video cannot exceed the video time.

Verify it.

Prepared video information.

Implementation results

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 --enable-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 --enable-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-libxvid --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
                    : 
    : {"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\7812f03a858f11ed8359e454e8bf1461.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    te_is_reencode  : 1
                    : 
    Hw              : 1
                    : 
    bitRate         : 16000000
                    : 
    : {"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= 329x    
video:6507kB audio:95kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.082792%
E:\360MoveData\Users\huyi\Desktop\7812f03a858f11ed8359e454e8bf1461.mp4

Resulting Video Messages

Knowledge supplementation

windows ffmpeg installation and deployment

1.Installation package download

As an important software ffmpeg for audio and video processing, it is a must to be installed.

2. Unzip the installation package

Download the installation package and extract it to the desired directory.

3. Configure environment variables

Find Control Panel -> click System -> click Advanced System Settings -> click Environment Variables

Configure the unzip or folder routing to the Path variable.

After confirming all the time, click win+r to open cmd.

Verify that the deployment was successful by entering the ffmpeg -i command.

to this article on the Python implementation of the video in accordance with the time dimension cut article is introduced to this, more related Python video time dimension cut content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!