golang实现 获取音频字节数后再得到音频时长
要获取音频字节数后再得到音频时长,可以使用audio包中的wav和mp3子包来实现。
首先,你需要导入以下包:
import (
"fmt"
"os"
"github.com/hajimehoshi/go-mp3"
"github.com/hajimehoshi/oto"
"github.com/go-audio/audio"
"github.com/go-audio/wav"
)
然后,你可以使用以下代码来获取音频字节数:
func GetAudioByteCount(filePath string) (int64, error) {
file, err := os.Open(filePath)
if err != nil {
return 0, err
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
return 0, err
}
return fileInfo.Size(), nil
}
接下来,你可以使用以下代码来获取音频时长:
func GetAudioDuration(filePath string) (float64, error) {
file, err := os.Open(filePath)
if err != nil {
return 0, err
}
defer file.Close()
var d audio.Duration
switch filepath.Ext(filePath) {
case ".wav":
dec := wav.NewDecoder(file)
if err := dec.Decode(&d); err != nil {
return 0, err
}
case ".mp3":
dec, err := mp3.NewDecoder(file)
if err != nil {
return 0, err
}
d = dec.Duration()
default:
return 0, fmt.Errorf("unsupported audio format")
}
return d.Seconds(), nil
}
最后,你可以使用以下代码来测试:
func main() {
filePath := "path/to/audio.wav"
byteCount, err := GetAudioByteCount(filePath)
if err != nil {
fmt.Println("Failed to get audio byte count:", err)
return
}
fmt.Println("Audio byte count:", byteCount)
duration, err := GetAudioDuration(filePath)
if err != nil {
fmt.Println("Failed to get audio duration:", err)
return
}
fmt.Println("Audio duration:", duration)
}
请确保替换filePath为实际的音频文件路径
原文地址: https://www.cveoy.top/t/topic/ihA6 著作权归作者所有。请勿转载和采集!