SoFunction
Updated on 2025-03-05

Sample code for using Golang to get audio and video duration information

1. Introduction to the tools

These tools are open source tools related to multimedia processing and streaming, and they all belong to the FFmpeg multimedia framework.

  • FFmpeg

It is a command line tool for processing multimedia content (audio, video, images, etc.). It can perform a variety of operations, including transcoding, editing, merging, separation, encoding, decoding, etc. FFmpeg is a powerful and widely used tool that can run on a variety of platforms.

  • FFplay

is a simple media player provided by FFmpeg, which can play audio and video files in various formats. FFplay is built on the FFmpeg library and provides a lightweight command-line interface for fast playback of multimedia files, suitable for testing and simple playback tasks.

  • FFprobe

is a tool for analyzing multimedia files. It provides detailed information, including codec, format, streaming information, etc. of multimedia files. FFprobe can help users understand the characteristics of multimedia files, such as resolution, frame rate, bit rate, etc., which is very useful for diagnosing and processing multimedia files.

  • FFserver

is a streaming media server that can be used to transcode and distribute audio/video streams in real time. It can accept multimedia streams from various sources (such as cameras, audio interfaces, etc.) and transcode them into different formats and resolutions, and then distribute them to clients over the network. FFserver can be used to build its own streaming platform, such as live audio and video services or video on demand services.

2. Use golang to obtain it for a long time

package main

import (
	"bufio"
	"fmt"
	"os/exec"
	"strconv"
)

// getDuration to get the duration of audio and video files by calling ffprobe
// The function receives a string parameter filePath, indicating the path of the audio and video file.// The function returns two values: an integer indicates duration (seconds), and an error indicates possible errors.func getDuration(filePath string) (int, error) {

	// Create a new command using ffprobe, call ffprobe with a series of parameters to indicate how long it only outputs the file.	cmd := ("/Users/lijie/workspace/ffmpeg-lijie/ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filePath)

	//Get the standard output stream of the command through the StdoutPipe method so that we can read the output of ffprobe.	stdout, err := ()
	//If an error occurs when fetching the output stream, an error is returned.	if err != nil {
		return 0, err
	}

	//Start the ffprobe command.  If startup fails, an error is returned.	if err := (); err != nil {
		return 0, err
	}

	//Create a new one to read the standard output of ffprobe.	scanner := (stdout)

	//Use the Scan method to read the first line of the output (i.e. the duration of the file).	if () {
		//() Gets the read string.		durationStr := ()
		//Use to convert the duration string to a floating point number.		duration, err := (durationStr, 64)
		//If the conversion fails, an error is returned.		if err != nil {
			return 0, err
		}
		//Convert the floating point time to an integer (seconds) and return, no errors.		return int(duration), nil
	}
	return 0, ("no duration found")

}

// The formatDurationSeconds function converts seconds into a string in the format of minutes and seconds.// The function receives an integer parameter seconds, indicating the duration (seconds).// The function returns a string, indicating the duration of the time, minute and second format.func formatDurationSeconds(seconds int) string {
	// Calculate the clock number by dividing the total number of seconds by 3600.	hours := seconds / 3600
	// Calculate the number of minutes by dividing the total number of seconds by 60.	minutes := (seconds % 3600) / 60
	//Calculate the remaining seconds by dividing the total number of seconds by the remainder of 60.	seconds = seconds % 60

	//Automatically determine whether the hours are included based on the number of seconds, and format the output accordingly	if hours > 0 {
		//Automatically determine whether the minutes are included based on the number of seconds, and format the output accordingly		if minutes > 0 {
			//Format the string in "MM:SS" format with minutes and seconds, and make sure that the minutes and seconds are both double digits (if less than two digits are less than 0, it will be added first).			return ("%02d:%02d:%02d", hours, minutes, seconds)
		} else {
			return ("%02d:%02d", hours, seconds)
		}
	} else if minutes > 0 {
		return ("%02d:%02d", minutes, seconds)
	} else {
		return ("00:%02d", seconds)
	}

}
func main() {
   //Define the path of the audio and video file and replace it with the actual file path.	filePath := "/opt/www/nginx/html/pages/resource/input.mp3"

	//Call the getDuration function to get the file in seconds.	durationSeconds, err := getDuration(filePath)
	//If an error occurs during the acquisition time, print the error and exit the program.	if err != nil {
		("Error getting duration:", err)
		return
	}
	("Duration:", durationSeconds)
	//Call the formatDurationSeconds function to convert the duration (seconds) into a string in the time, minute and second format.	durationFormatted := formatDurationSeconds(durationSeconds)
	("Duration: %s\n", durationFormatted)
}

This is the article about using Golang to obtain audio and video duration information. For more information about Golang to obtain long time, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!