首頁 > 後端開發 > Golang > 主體

在 Go 中計算 Ogg 音訊持續時間:逐步指南

PHPz
發布: 2024-09-05 21:31:09
原創
347 人瀏覽過

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

我試圖克隆不和諧,我發現他們使用 ogg 格式的音訊(我認為),我試圖將音訊持續時間儲存在資料庫中。

關於獲取 OGG 音訊持續時間的 stackoverflow 解決方案,我發現很有趣。該方法包括查找文件末尾,找到最後一個 Ogg 頁頭,並讀取其顆粒位置。

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 < len(data)-14 && rate == 0; i++ {
        if data[i] == 'v' && data[i+1] == 'o' && data[i+2] == 'r' && data[i+3] == 'b' && data[i+4] == 'i' && data[i+5] == 's' {
            rate = int64(readLittleEndianInt(data[i+11 : i+15]))
        }
    }

    if length == 0 || rate == 0 {
        return 0, fmt.Errorf("could not find necessary information in Ogg file")
    }

    durationMs := length * 1000 / rate
    return durationMs, nil
}

func readLittleEndianInt(data []byte) int64 {
    return int64(uint32(data[0]) | uint32(data[1])<<8 | uint32(data[2])<<16 | uint32(data[3])<<24)
}

登入後複製

我決定在這裡分享它,我發現這個實現非常酷,也許可以幫助其他人

以上是在 Go 中計算 Ogg 音訊持續時間:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!