Home > Backend Development > Golang > How to get duration of mp3 file in Golang?

How to get duration of mp3 file in Golang?

WBOY
Release: 2024-02-09 11:57:18
forward
738 people have browsed it

How to get duration of mp3 file in Golang?

Getting the duration of mp3 files in Golang is a common requirement. PHP editor Xiaoxin will introduce you to a simple and effective method. First, we need to use a third-party library to process mp3 files. It is recommended to use the go-audio library, which provides some convenient functions. Next, we need to use the Decoder function of the go-audio library to decode the mp3 file. Then, we can get the duration of the mp3 file by calling the Decoder's Duration method. Finally, we will get a duration value in nanoseconds, which we can convert to a more friendly format, like seconds or minutes. This is how to get mp3 file duration in Golang. Hope this helps!

Question content

I set up a text-to-speech request that asks the openAI API to then generate audio. Now I want to know its duration in [MM:SS], is there any way or library to get it?

Solution

This question is answered here:

How to find the length of mp3 file golang?

Additionally, you may want to convert float64 to 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)
}
Copy after login

The above is the detailed content of How to get duration of mp3 file in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template