首頁  >  文章  >  後端開發  >  如何在Golang中取得mp3檔案的持續時間?

如何在Golang中取得mp3檔案的持續時間?

WBOY
WBOY轉載
2024-02-09 11:57:18663瀏覽

如何在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刪除