Skip to content

Get duration of a video #22

@jinyus

Description

@jinyus

Hey, thanks for this package, I wrote some code about a year ago to find the duration of a video using your package but I see that you've changed the api without bumping the major version. Could you help me updating this code below for the new api?

func GetVideoDuration(path string) (int, error) {
file, err := os.Open(path)
if err != nil {
	return 0, fmt.Errorf("could not open file to extract duration: %v", err)
}
defer file.Close()

info, err := file.Stat()
if err != nil {
	return 0, fmt.Errorf("could not get file stats to extract duration: %v", err)
}

f := &atom.File{File: file, Size: info.Size()}

for offset := int64(0); offset < f.Size; {
	boxSize, boxType := f.ReadBoxAt(offset)
	if boxType == "moov" {
		offset += atom.BoxHeaderSize

		for offset < (f.Size - atom.BoxHeaderSize) {
			boxSize, boxType = f.ReadBoxAt(offset)
			if boxType == "mvhd" {
				mvhd := &atom.Box{
					Name:  boxType,
					Size:  int64(boxSize),
					File:  f,
					Start: offset,
				}
				data := mvhd.ReadBoxData()

				ts := binary.BigEndian.Uint32(data[12:16])
				duration := binary.BigEndian.Uint32(data[16:20])
				return int(math.Round(float64(duration) / float64(ts))), nil
			}

			offset += int64(boxSize)
		}
	}

	offset += int64(boxSize)
}
return 0, errors.New("mvhd box not found in mp4 container")
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions