登录
首页 >  Golang >  Go教程

在 Go 中计算 Ogg 音频持续时间:分步指南

来源:dev.to

时间:2024-09-09 10:39:50 391浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在 Go 中计算 Ogg 音频持续时间:分步指南》,聊聊,我们一起来看看吧!

在 Go 中计算 Ogg 音频持续时间:分步指南

我试图克隆不和谐,我发现他们使用 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 音频持续时间:分步指南》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>