Search code examples
goaudiotext-to-speechopenai-apiopenai-whisper

How to get the duration of an mp3 file in Golang?


I set up a text to speech an request that to openAI API then it generates an audio. Now I want to know it's duration in [MM:SS], is there a way or a library to get it?


Solution

  • This question is answered here:

    How to find the length of mp3 file in golang?

    Also, you would want to transform a float64 in MM:SS format. In this case you can use something like this:

    package main
    
    import (
        "fmt"
        "io"
        "os"
        "time"
    
        "github.com/tcolgate/mp3"
    )
    
    const mp3File = <path-to-mp3-file>
    
    func main() {
        var t float64
    
        fd, err := os.Open(mp3File)
        if err != nil {
            panic(err)
        }
        defer fd.Close()
    
        d := mp3.NewDecoder(fd)
        var f mp3.Frame
        skipped := 0
    
        for {
    
            if err := d.Decode(&f, &skipped); err != nil {
                if err == io.EOF {
                    break
                }
                fmt.Println(err)
                return
            }
    
            t = t + f.Duration().Seconds()
        }
    
        fmt.Println(t)
    
        // Convert the value to a time.Duration object
        duration := time.Duration(t * float64(time.Second))
    
        // Get the duration in minutes and seconds
        minutes := int(duration.Minutes())
        seconds := int(duration.Seconds()) - (minutes * 60)
    
        // Format the duration in the MM:SS format
        formatted_duration := fmt.Sprintf("%02d:%02d", minutes, seconds)
    
        fmt.Printf("The value %v expressed in MM:SS format is %v.\n", t, formatted_duration)
    }