要获取WAV文件的时长,可以使用标准库中的audio/wav包。下面是一个示例代码,演示了如何读取WAV文件并获取其时长:

package main

import (
	"fmt"
	"os"
	"encoding/binary"
	"io"
)

func main() {
	// 打开WAV文件
	file, err := os.Open("example.wav")
	if err != nil {
		fmt.Println("无法打开文件:", err)
		return
	}
	defer file.Close()

	// 读取WAV头部信息
	header := make([]byte, 44)
	_, err = file.Read(header)
	if err != nil {
		fmt.Println("无法读取WAV头部:", err)
		return
	}

	// 解析WAV头部信息
	audioFormat := binary.LittleEndian.Uint16(header[20:22])
	numChannels := binary.LittleEndian.Uint16(header[22:24])
	sampleRate := binary.LittleEndian.Uint32(header[24:28])
	byteRate := binary.LittleEndian.Uint32(header[28:32])
	blockAlign := binary.LittleEndian.Uint16(header[32:34])
	bitsPerSample := binary.LittleEndian.Uint16(header[34:36])

	// 计算WAV文件时长
	dataSize := binary.LittleEndian.Uint32(header[40:44])
	duration := float64(dataSize) / float64(byteRate)

	// 输出结果
	fmt.Printf("音频格式: %d\n", audioFormat)
	fmt.Printf("声道数: %d\n", numChannels)
	fmt.Printf("采样率: %d Hz\n", sampleRate)
	fmt.Printf("比特率: %d bps\n", byteRate*8)
	fmt.Printf("块对齐: %d bytes\n", blockAlign)
	fmt.Printf("采样位数: %d bits\n", bitsPerSample)
	fmt.Printf("文件时长: %.2f 秒\n", duration)
}

你需要将上述代码中的example.wav替换为你要获取时长的WAV文件的路径。代码中使用了binary.LittleEndian来读取二进制数据,确保你的WAV文件是使用小端字节序存储的。代码中输出的时长单位是秒

golang 获取wav文件的时长

原文地址: http://www.cveoy.top/t/topic/ieWZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录