"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Calculating Ogg Audio Duration in Go: A Step-by-Step Guide

Calculating Ogg Audio Duration in Go: A Step-by-Step Guide

Published on 2024-11-01
Browse:999

Calculating Ogg Audio Duration in Go: A Step-by-Step Guide

I was trying to clone discord and i found out they use ogg formats for audio (i think), im trying to get the audio duration to store in the database.

A stackoverflow solution about getting the OGG audio duration, i found fascinating. The approach involves seeking to the end of the file, finding the last Ogg page header, and reading its granule position.

func getOggDurationMs(reader io.Reader) (int64, error) {
    // Read the entire Ogg file into a byte slice
    data, err := io.ReadAll(reader)
    if err != nil {
        return 0, fmt.Errorf("error reading Ogg file: %w", err)
    }

    // Search for the "OggS" signature and calculate the length
    var length int64
    for i := len(data) - 14; i >= 0 && length == 0; i-- {
        if data[i] == 'O' && data[i 1] == 'g' && data[i 2] == 'g' && data[i 3] == 'S' {
            length = int64(readLittleEndianInt(data[i 6 : i 14]))
        }
    }

    // Search for the "vorbis" signature and calculate the rate
    var rate int64
    for i := 0; i 



I decided to share it here, i just found the implementation very cool and maybe help some other people out

Release Statement This article is reproduced at: https://dev.to/mmvergara/calculating-ogg-audio-duration-in-go-a-step-by-step-guide-1igh?1 If there is any infringement, please contact [email protected] delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3