Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Created August 10, 2025 06:21
Show Gist options
  • Select an option

  • Save wjkoh/803123d48f0308cc0352aa3d381eded3 to your computer and use it in GitHub Desktop.

Select an option

Save wjkoh/803123d48f0308cc0352aa3d381eded3 to your computer and use it in GitHub Desktop.
Go + FFmpeg: How to Find the Duration of Audio and Video
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