登录
首页 >  Golang >  Go问答

如何用Golang获取mp3文件的时长?

来源:stackoverflow

时间:2024-02-05 15:11:56 162浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《如何用Golang获取mp3文件的时长?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

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


正确答案


这个问题在这里得到解答:

如何查找 mp3 文件的长度golang?

此外,您可能希望将 float64 转换为 MM:SS 格式。在这种情况下,您可以使用如下内容:

package main

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

    "github.com/tcolgate/mp3"
)

const mp3File = 

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

到这里,我们也就讲完了《如何用Golang获取mp3文件的时长?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>