golang之媒体处理

发布时间 2023-12-05 10:30:34作者: X-Wolf

[视频]

获取视频封面图:

1) 如果是使用oss的话, 可以添加指定的后缀生成指定图片

 

 

获取视频长度:

1)若是oss上的视频,则可以使用阿里云的IMM中的提取视频信息的服务

注意这里获取需要使用到签名之后获取对应的数据

 

这里使用基于阿里云oss包: 

github.com/aliyun/aliyun-oss-go-sdk/oss
 
 

 

2)对于在线视频

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
    "io"
    "os"
)

// 获取本地文件视频秒数

// BoxHeader 信息头
type BoxHeader struct {
    Size       uint32
    FourccType [4]byte
    Size64     uint64
}

func main() {
    url := "./video.mp4"
    file, err := os.Open(url)
    if err != nil {
        panic(err)
    }
    duration, err := GetMP4Duration(file)
    if err != nil {
        panic(err)
    }
    fmt.Println(duration)
}

// GetMP4Duration 获取视频时长,以秒计
func GetMP4Duration(reader io.ReaderAt) (lengthOfTime uint32, err error) {
    var info = make([]byte, 0x10)
    var boxHeader BoxHeader
    var offset int64 = 0
    // 获取moov结构偏移
    for {
        _, err = reader.ReadAt(info, offset)
        if err != nil {
            return
        }
        boxHeader = getHeaderBoxInfo(info)
        fourccType := getFourccType(boxHeader)
        if fourccType == "moov" {
            break
        }
        // 有一部分mp4 mdat尺寸过大需要特殊处理
        if fourccType == "mdat" {
            if boxHeader.Size == 1 {
                offset += int64(boxHeader.Size64)
                continue
            }
        }
        offset += int64(boxHeader.Size)
    }
    // 获取moov结构开头一部分
    moovStartBytes := make([]byte, 0x100)
    _, err = reader.ReadAt(moovStartBytes, offset)
    if err != nil {
        return
    }
    // 定义timeScale与Duration偏移
    timeScaleOffset := 0x1C
    durationOffest := 0x20
    timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
    Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
    lengthOfTime = Duration / timeScale
    return
}

// getHeaderBoxInfo 获取头信息
func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
    buf := bytes.NewBuffer(data)
    binary.Read(buf, binary.BigEndian, &boxHeader)
    return
}

// getFourccType 获取信息头类型
func getFourccType(boxHeader BoxHeader) (fourccType string) {
    fourccType = string(boxHeader.FourccType[:])
    return
}

另外还有其他第三方库可以使用:

go get -u github.com/Stitch-Zhang/gmp4