如何在Golang中获取OpenAI TTS生成的MP3文件时长(MM:SS格式)?
在Golang中获取MP3文件时长并格式化为[MM:SS]
方案一:使用纯Go MP3解析库(推荐)
使用github.com/hajimehoshi/go-mp3库,这是成熟的纯Go MP3解码器,无需依赖外部工具,跨平台友好。
步骤:
- 安装库:
go get github.com/hajimehoshi/go-mp3
- 示例代码:
package main import ( "fmt" "os" "time" "github.com/hajimehoshi/go-mp3" ) func getMP3Duration(filePath string) (string, error) { f, err := os.Open(filePath) if err != nil { return "", err } defer f.Close() decoder, err := mp3.NewDecoder(f) if err != nil { return "", err } totalSamples := decoder.Length() sampleRate := decoder.SampleRate() totalSeconds := float64(totalSamples) / float64(sampleRate) duration := time.Duration(totalSeconds * float64(time.Second)) minutes := int(duration.Minutes()) seconds := int(duration.Seconds()) % 60 return fmt.Sprintf("[%02d:%02d]", minutes, seconds), nil } func main() { duration, err := getMP3Duration("output.mp3") if err != nil { fmt.Printf("获取时长失败:%v\n", err) return } fmt.Println(duration) }
方案二:调用FFmpeg(适合已有FFmpeg环境的场景)
如果系统已安装FFmpeg,可以通过执行命令解析输出获取时长,这种方式支持更多音频格式,但依赖外部工具。
示例代码:
package main import ( "fmt" "os/exec" "regexp" "strconv" ) func getMP3DurationWithFFmpeg(filePath string) (string, error) { cmd := exec.Command("ffmpeg", "-i", filePath) output, err := cmd.CombinedOutput() // FFmpeg处理输入时通常会返回非零退出码,此处忽略错误仅解析输出内容 re := regexp.MustCompile(`Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,`) match := re.FindStringSubmatch(string(output)) if len(match) < 4 { return "", fmt.Errorf("无法解析音频时长") } hours, _ := strconv.Atoi(match[1]) minutes, _ := strconv.Atoi(match[2]) seconds, _ := strconv.Atoi(match[3]) totalMinutes := hours*60 + minutes return fmt.Sprintf("[%02d:%02d]", totalMinutes, seconds), nil } func main() { duration, err := getMP3DurationWithFFmpeg("output.mp3") if err != nil { fmt.Printf("获取时长失败:%v\n", err) return } fmt.Println(duration) }
内容的提问来源于stack exchange,提问作者San
相关产品推荐
相关产品推荐

