Created
August 10, 2025 06:21
-
-
Save wjkoh/803123d48f0308cc0352aa3d381eded3 to your computer and use it in GitHub Desktop.
Go + FFmpeg: How to Find the Duration of Audio and Video
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func Duration(ctx context.Context, filename string) (time.Duration, error) { | |
| ctx, cancel := context.WithCancel(ctx) | |
| defer cancel() | |
| cmd := exec.CommandContext(ctx, "ffprobe", "-i", filename, "-show_format", "-output_format", "json") | |
| stdout, err := cmd.StdoutPipe() | |
| if err != nil { | |
| return time.Duration(0), nil | |
| } | |
| if err := cmd.Start(); err != nil { | |
| return time.Duration(0), nil | |
| } | |
| var output struct { | |
| Format struct { | |
| Duration string `json:"duration"` | |
| } `json:"format"` | |
| } | |
| if err := json.NewDecoder(stdout).Decode(&output); err != nil { | |
| return time.Duration(0), nil | |
| } | |
| if err := cmd.Wait(); err != nil { | |
| return time.Duration(0), nil | |
| } | |
| return time.ParseDuration(output.Format.Duration + "s") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment