mp3mp4_duration.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "mime/multipart"
  6. )
  7. // GetMediaDuration 得到媒体文件时长
  8. func GetMediaDuration(reader multipart.File, contentType string) (int, error) {
  9. var duration int
  10. var err error
  11. if contentType == "video/mp4" {
  12. duration, err = GetMP4Duration(reader)
  13. }
  14. if contentType == "audio/mpeg" {
  15. playDuration, _ := GetMP3PlayDuration(reader)
  16. duration = int(playDuration)
  17. }
  18. if err != nil {
  19. return 0, err
  20. }
  21. return duration * 1000, err
  22. }
  23. // GetMP4Duration 获取视频时长,以秒计
  24. func GetMP4Duration(reader multipart.File) (lengthOfTime int, err error) {
  25. var info = make([]byte, 0x10)
  26. var boxHeader BoxHeader
  27. var offset int64 = 0
  28. // 获取moov结构偏移
  29. for {
  30. _, err = reader.ReadAt(info, offset)
  31. if err != nil {
  32. return
  33. }
  34. boxHeader = getHeaderBoxInfo(info)
  35. fourccType := getFourccType(boxHeader)
  36. if fourccType == "moov" {
  37. break
  38. }
  39. // 有一部分mp4 mdat尺寸过大需要特殊处理
  40. if fourccType == "mdat" {
  41. if boxHeader.Size == 1 {
  42. offset += int64(boxHeader.Size64)
  43. continue
  44. }
  45. }
  46. offset += int64(boxHeader.Size)
  47. }
  48. // 获取moov结构开头一部分
  49. moovStartBytes := make([]byte, 0x100)
  50. _, err = reader.ReadAt(moovStartBytes, offset)
  51. if err != nil {
  52. return
  53. }
  54. // 定义timeScale与Duration偏移
  55. timeScaleOffset := 0x1C
  56. durationOffest := 0x20
  57. timeScale := binary.BigEndian.Uint32(moovStartBytes[timeScaleOffset : timeScaleOffset+4])
  58. Duration := binary.BigEndian.Uint32(moovStartBytes[durationOffest : durationOffest+4])
  59. lengthOfTime = int(Duration / timeScale)
  60. return
  61. }
  62. // BoxHeader 信息头
  63. type BoxHeader struct {
  64. Size uint32
  65. FourccType [4]byte
  66. Size64 uint64
  67. }
  68. func getHeaderBoxInfo(data []byte) (boxHeader BoxHeader) {
  69. buf := bytes.NewBuffer(data)
  70. binary.Read(buf, binary.BigEndian, &boxHeader)
  71. return
  72. }
  73. // getFourccType 获取信息头类型
  74. func getFourccType(boxHeader BoxHeader) (fourccType string) {
  75. fourccType = string(boxHeader.FourccType[:])
  76. return
  77. }