SoFunction
Updated on 2025-04-07

The implementation of audio and video processing of Golang integrated FFmpeg

The implementation of audio and video processing of Golang integrated FFmpeg

Updated: February 17, 2025 10:55:18 Author: Yy_Yyyyy_zz
FFmpeg is an open source audio and video processing tool, widely used in video conversion, screenshots, processing and streaming media push operations. This article mainly introduces the implementation of Golang's integrated audio and video processing, which has certain reference value. If you are interested, you can learn about it.

Overview

FFmpeg is an open source audio and video processing tool, widely used in video conversion, screenshots, processing and streaming media push. In Go language project, FFmpeg can implement related operations by calling system commands. This article will introduce how to integrate and use FFmpeg in Go, especially for the application of intercepting keyframes and generating images in video processing.

Steps to use

  • Install FFmpegFirst make sure FFmpeg is installed and configured in the system's environment variables. You can check whether FFmpeg is installed by running the following command:

    ffmpeg -version
    

    If it is not installed, you can choose the corresponding installation method according to the operating system.

  • Install Go language dependency libraryIn Go language, the call to FFmpeg is usually executedTo implement it, so you only need to use the Go standard libraryos/execYou can execute the FFmpeg command. No additional third-party libraries are required.

  • Call the FFmpeg commanduseto execute the FFmpeg command and capture the command execution result.

FFmpeg common instructions

Here are some commonly used command line parameters of FFmpeg that can help you better utilize FFmpeg in your Go project:

  • Video transcodingConvert video formats (for example: convert MP4 to AVI):

    ffmpeg -i input.mp4 
    
  • Take a video screenshotKeyframes of the video:

    ffmpeg -i input.mp4 -vf "select='eq(pict_type,I)'" -vsync vfr output_%
    
  • Set the interval time of screenshotsImages are captured every certain time:

    ffmpeg -i input.mp4 -vf "fps=1/5" output_%
    
  • Extract audio from videoExtract audio from video and save it to MP3 format:

    ffmpeg -i input.mp4 -vn output.mp3
    

Keyframe interception logic code implementation

Next, we will explain in detail a sample code based on Go and FFmpeg. This sample code will intercept keyframes from the video at a certain time and return the corresponding picture.

Code implementation

The following is the Go language code that implements "Seave video keyframes according to specified time intervals".

// GetMp4ImagesIntervalSeconds
// @Description: Specify the duration to capture the image// @param videoBase64 base64 video// @param intervalSeconds Number of seconds between screenshots// @return imageSlice Screenshot and slicefunc GetMp4ImagesIntervalSeconds(videoBase64 string, intervalSeconds int) (imageSlice []ImageInfo, err error) {
    // Decode base64 string    videoData, err := (videoBase64)
    if err != nil {
        ("GetMp4ImagesIntervalSeconds DecodeString err:%v", ())
        return nil, err
    }

    //Judge whether the directory exists    if _, err = ("./temp"); (err) {
        err = ("./temp", 0755)
        if err != nil {
            ("GetMp4ImagesIntervalSeconds  err:%v", ())
            return nil, err
        }
    }

    // Create temporary video files    tmpVideoFile, err := ("./temp", "tempvideo_*.mp4")
    if err != nil {
        ("GetMp4ImagesIntervalSeconds  err:%v", ())
        return nil, err
    }
    defer (())
    defer ()

    // Write video data to temporary files    _, err = (videoData)
    if err != nil {
        ("GetMp4ImagesIntervalSeconds  err:%v", ())
        return nil, err
    }

    // Create a temporary picture directory    tempImageDir, err := ("./temp", "tempimage_")
    if err != nil {
        ("GetMp4ImagesIntervalSeconds  err:%v", ())
        return nil, err
    }
    defer (tempImageDir)

    // Use ffmpeg to intercept keyframes and put the image into the specified directory    /*
         -i (): Specifies the name of the input file as the temporary video file.
         -vf select='eq(pict_type,I)',fps=1/intervalSeconds: Use the select filter to select the keyframe and specify the frame rate to be 1/intervalSeconds, that is, one frame is taken every intervalSeconds seconds.
         (tempImageDir, "temp_%"): Specifies the format of the output image file name. temp_% means that the format of the output file name is temp_001.jpg, temp_002.jpg, etc. %03d will be replaced with an incremental number sequence.  Here tempImageDir is a temporary directory for saving images.
     */
    cmd := ("ffmpeg", "-i", (), "-vf", ("select='eq(pict_type,I)',fps=1/%d", intervalSeconds), (tempImageDir, "temp_%"))
    err = ()
    if err != nil {
        ("GetMp4ImagesIntervalSeconds  err:%v", ())
        return nil, err
    }

    // traverse the temporary image directory and add the image file name to the slice    files, _ := ((tempImageDir, "temp_*.jpg"))
    for _, fileName := range files {
        imageBase64, dhash, err := fileToBase64(fileName)
        if err != nil {
            ("GetMp4ImagesIntervalSeconds fileToBase64(fileName) err:%v", ())
            return nil, err
        }
        imageSlice = append(imageSlice, ImageInfo{
            ImageBase64: imageBase64,
            DHash:       dhash,
        })
        ("dhash:", dhash)
    }
    ("GetMp4ImagesIntervalSeconds success number:%v", len(imageSlice))
    return imageSlice, nil
}

Code description

  • Video data processingpassDecode the Base64 data of the video, obtain the binary stream of the video, and write it to a temporary MP4 file.

  • Create a temporary directoryCreate two temporary directories: one for storing video files and the other for storing image files that are intercepted from the video.

  • Use the FFmpeg command line to intercept video keyframespassCall the FFmpeg command, parameters-vf select='eq(pict_type,I)',fps=1/{intervalSeconds}Indicates that I frame (keyframe) is selected and screenshots are taken at the specified time interval. The image file is saved to the temporary image directory.

  • Return to screenshot resultsThe intercepted image is saved in JPG format. The program traverses the image folder and converts each image into a Base64 string, and generatesImageInfoStructure returns.

Summarize

This article describes how to integrate and use FFmpeg for video processing in a Go project, especially by intercepting keyframes of videos through FFmpeg and saving them as images. In this way, it is very convenient to quickly analyze and process videos, which are suitable for scenes such as image recognition, video content analysis, etc. I hope it will be helpful to everyone's project development!

This is the end of this article about the implementation of Golang integrated FFmpeg audio and video processing. For more related Golang FFmpeg audio and video content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • Golang
  • FFmpeg
  • Audio and video

Related Articles

  • How to implement daily limit for users (for example, you can only receive benefits three times a day)

    This article mainly introduces how Go implements daily limits for users (for example, you can only receive benefits three times a day)
    2022-01-01
  • The difference between panic and recovery in Golang

    This article mainly introduces the difference between panic and recovery in Golang. The article expands the difference between panic and recovery based on the basic content of Golang. If you need it, please refer to it.
    2022-06-06
  • One article will help you understand the application of methods in GO language

    The methods in the GO language are actually similar to functions, except that there is an additional parameter based on the functions. This article mainly introduces the application of methods in the GO language. If you need them, please refer to them.
    2023-09-09
  • Problems and solutions in string assignment in Go language

    This article mainly introduces some problems and solutions to string assignment in Go language. The sample code in the article is explained in detail. Interested friends can refer to it.
    2024-12-12
  • Go language serializes and deserializes JSON data

    This article introduces the method of Go to serialize and deserialize JSON data, and the article introduces it in detail through sample code. It has certain reference value for everyone's study or work. Friends who need it can refer to it.
    2022-07-07
  • About go get download third-party package storage path

    This article mainly introduces the problem of downloading third-party package storage paths of go get, which is of great reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.
    2024-01-01
  • How to use omitempty in go

    In Go programming, the `omitempty` tag is used to control whether the field is included during JSON encoding and decoding. When the structure field is marked `omitempty` and the field value is empty, the field will not appear in the generated JSON, which helps to optimize the JSON structure and reduce the data volume. The working mechanism and actual effect of `omitempty` is explained through specific examples.
    2024-09-09
  • Example code for scanning QR code in GO language

    Are you confused about the process of scanning QR codes? This article is shared with the author's own development experience to let everyone be familiar with and master this function. Interested friends, please follow the editor to learn it.
    2023-06-06
  • Deep analysis of arrays, strings and slices in Golang

    Golang is a programming language known for its simplicity, concurrency and performance. One of its important features is its ability to handle data types such as arrays, strings, and slices. This article will dive into these data types and explore how to use them in your code
    2023-04-04
  • Detailed explanation of how Go language can ensure quality through testing

    This article mainly introduces you how to ensure quality through testing. Friends in need can learn from it for reference. I hope it can be helpful. I wish you more progress and get a promotion as soon as possible.
    2022-08-08

Latest Comments