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

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

We need to customize the error type because the standard error interface provides limited information, and custom types can add more context and structured information. 1) Custom error types can contain error codes, locations, context data, etc., 2) Improve debugging efficiency and user experience, 3) But attention should be paid to its complexity and maintenance costs.

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
