golang 获取mp4 视频时长信息:
本文参考自:https://www.cnblogs.com/Akkuman/p/12371838.html
主要原理是根据MP4文档格式取到moov结构,然后获取时长
package main
import ( "bytes" "encoding/binary" "fmt" "io" "os" "path/filepath" )
type BoxHeader struct { Size uint32 FourccType [4]byte Size64 uint64 }
func main() { file, err := os.Open(os.Args[1]) if err != nil { panic(err) } duration, err := GetMP4Duration(file) if err != nil { panic(err) } fmt.Println(filepath.Base(os.Args[1]), duration) }
func GetMP4Duration(reader io.ReaderAt) (lengthOfTime uint32, err error) { var info = make([]byte, 0x10) var boxHeader BoxHeader var offset int64 = 0 for { _, err = reader.ReadAt(info, offset) if err != nil { return } boxHeader = getHeaderBoxInfo(info) fourccType := getFourccType(boxHeader) if fourccType == "moov" { break } if fourccType == "mdat" { if boxHeader.Size == 1 { offset += int64(boxHeader.Size64) continue } } offset += int64(boxHeader.Size) } moovStartBytes := make([]byte, 0x100) _, err = reader.ReadAt(moovStartBytes, offset) if err != nil { return } timeScaleOffset := 0x1C durationOffest := 0x20 timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4]) Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4]) lengthOfTime = Duration / timeScale return }
func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) { buf := bytes.NewBuffer(data) binary.Read(buf, binary.BigEndian, &boxHeader) return }
func getFourccType(boxHeader BoxHeader) (fourccType string) { fourccType = string(boxHeader.FourccType[:]) return }
|
获取到的时间为 秒, 如果想要换成 h:m:s,格式需要转换一下:
func GetMP4Time(filePath string) string { file, err := os.Open(filePath) if err != nil { panic(err) } duration, err := GetMP4Duration(file) if err != nil { panic(err) } fmt.Println(filepath.Base(filePath), duration)
d := time.Duration(duration) * time.Second h := d / time.Hour d -= h * time.Hour m := d / time.Minute d -= m * time.Minute s := d / time.Second
return fmt.Sprintf("%02d:%02d:%02d", h, m, s) }
|