首页  >  文章  >  后端开发  >  如何在Golang中获取mp3文件的持续时间?

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

WBOY
WBOY转载
2024-02-09 11:57:18668浏览

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

在Golang中获取mp3文件的持续时间是一个常见的需求。php小编小新将为您介绍一种简单有效的方法。首先,我们需要使用第三方库来处理mp3文件。推荐使用go-audio库,它提供了一些便捷的功能。接下来,我们需要使用go-audio库的Decoder函数来解码mp3文件。然后,我们可以通过调用Decoder的Duration方法来获取mp3文件的持续时间。最后,我们将得到一个以纳秒为单位的持续时间值,我们可以将其转换为更友好的格式,比如秒或分钟。这就是在Golang中获取mp3文件持续时间的方法。希望对您有所帮助!

问题内容

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

解决方法

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

如何查找 mp3 文件的长度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)
}

以上是如何在Golang中获取mp3文件的持续时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除