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

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

I used to be attempting to clone discord and that i discovered they use ogg codecs for audio (i feel), im attempting to get the audio length to retailer within the database.

A stackoverflow resolution about getting the OGG audio length, i discovered fascinating. The method includes in search of to the top of the file, discovering the final Ogg web page header, and studying its granule place.


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

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

    // Search for the "vorbis" signature and calculate the speed
    var charge int64
    for i := 0; i < len(knowledge)-14 && charge == 0; i++ {
        if knowledge[i] == 'v' && knowledge[i+1] == 'o' && knowledge[i+2] == 'r' && knowledge[i+3] == 'b' && knowledge[i+4] == 'i' && knowledge[i+5] == 's' {
            charge = int64(readLittleEndianInt(knowledge[i+11 : i+15]))
        }
    }

    if size == 0 || charge == 0 {
        return 0, fmt.Errorf("couldn't discover essential data in Ogg file")
    }

    durationMs := size * 1000 / charge
    return durationMs, nil
}

func readLittleEndianInt(knowledge []byte) int64  uint32(knowledge[3])<<24)


I made a decision to share it right here, i simply discovered the implementation very cool and perhaps assist another individuals out

HI-FI News

through DEV Community https://dev.to

September 5, 2024 at 12:18PM