How to Get Video Duration in Go with FFmpeg
In the world of video processing, determining the duration of a video file is a fundamental task that is often required for various applications, such as streaming services, video editing, or simply understanding the length of a video clip. For developers working with Go, a popular choice for its simplicity and efficiency, integrating FFmpeg to get the video duration can be a bit daunting at first. However, with the right approach, it’s quite straightforward. This article will guide you through the process of how to get video duration in Go using FFmpeg.
Firstly, you need to have FFmpeg installed on your system. FFmpeg is a powerful multimedia framework that can decode, encode, transcode, mux, demux, stream, filter, and play almost anything that humans and machines have created. It’s a must-have tool for anyone dealing with video files.
To get started, you’ll need to use the FFmpeg command-line tool to extract the duration of a video file. The `ffprobe` utility, which is part of FFmpeg, can be used to retrieve metadata from multimedia files, including the duration.
Here’s a step-by-step guide on how to get video duration in Go with FFmpeg:
1. Install FFmpeg: Make sure FFmpeg is installed on your system. You can download it from the official FFmpeg website or use a package manager like Homebrew on macOS.
2. Write Go Code: Create a new Go file, for example, `get_video_duration.go`, and write the following code:
“`go
package main
import (
“bytes”
“os/exec”
“strings”
)
// GetVideoDuration returns the duration of a video file in seconds.
func GetVideoDuration(filePath string) (float64, error) {
cmd := exec.Command(“ffprobe”, “-v”, “error”, “-show_entries”, “format=duration”, “-of”, “default=noprint_wrappers=1:nokey=1”, filePath)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return 0, err
}
durationStr := strings.TrimSpace(out.String())
duration, err := strconv.ParseFloat(durationStr, 64)
if err != nil {
return 0, err
}
return duration, nil
}
func main() {
filePath := “path/to/your/video.mp4”
duration, err := GetVideoDuration(filePath)
if err != nil {
panic(err)
}
println(“Video duration:”, duration, “seconds”)
}
“`
3. Run the Code: Save the file and run it using the Go command:
“`bash
go run get_video_duration.go
“`
This script uses the `exec.Command` function to execute the `ffprobe` command with the appropriate arguments. It then reads the output, extracts the duration, and converts it to a float64 value representing the duration in seconds.
Remember to replace `”path/to/your/video.mp4″` with the actual path to your video file.
In conclusion, getting the video duration in Go using FFmpeg is a simple task once you have the right setup. By leveraging the power of FFmpeg and the ease of Go, you can quickly and efficiently extract video metadata, such as duration, for your applications.