如何在Golang中获取mp3文件的持续时间?

vd2z7a6w  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(184)

我设置了一个文本到语音的请求,请求openAI API,然后它生成一个音频。现在我想知道它的持续时间在[MM:SS],有没有方法或库可以获得它?

h6my8fg2

h6my8fg21#

您可以查看go-audio library
从那里,您可以从文件中查找最后一帧

import (
    "fmt"
    "os"
    "github.com/go-audio/audio"
)

func main() {
    filePath := "....mp3"
    file, _ := os.Open(filePath)
    decoder := audio.NewDecoder(file, filePath)
    _ = decoder.SeekLastFrame()
    duration := decoder.Duration()
    fmt.Printf("Duration of %s: %v\n", filePath, duration)
}

字符串

h5qlskok

h5qlskok2#

这个问题在这里得到了回答:
How to find the length of mp3 file in golang?
另外,你可能想将float64转换为MM:SS格式。在这种情况下,你可以使用这样的方法:

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)
}

字符串

6ss1mwsb

6ss1mwsb3#

package main

import (
    "fmt"
    "io"
    "log"
    "os"
    "time"

    "github.com/tcolgate/mp3"
)

func Duration(mp3FilePath string) (string, error) {
    file, err := os.Open(mp3FilePath)
    if err != nil {
        return "", err
    }
    defer file.Close()

    decoder := mp3.NewDecoder(file)
    totalDuration := 0.0

    var frame mp3.Frame
    var skipped int
    for {
        if err := decoder.Decode(&frame, &skipped); err != nil {
            if err == io.EOF {
                break
            }
            return "", err
        }
        totalDuration += frame.Duration().Seconds()
    }

    duration := time.Second * time.Duration(totalDuration)
    return fmt.Sprintf("[%02d:%02d]", int(duration.Minutes()), int(duration.Seconds())%60), nil
}

func main() {
    path := "path/of/your/mp3/file"
    duration, err := Duration(path)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(duration)
}

字符串


的数据


相关问题