在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 =
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)
}
登錄后復制






