Skip to content

音频流转mp3格式

javascript
function convertToMp3(wavDataView) {
  // 获取wav头信息
  const wav = lamejs.WavHeader.readHeader(wavDataView)
  const { channels, sampleRate } = wav
  const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128)
  // 获取左右通道数据
  const result = recorder.getChannelData()
  const buffer = []

  const leftData =
    result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2)
  const rightData =
    result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2)
  const remaining = leftData.length + (rightData ? rightData.length : 0)

  const maxSamples = 1152
  for (let i = 0; i < remaining; i += maxSamples) {
    const left = leftData.subarray(i, i + maxSamples)
    let right = null
    let mp3buf = null

    if (channels === 2) {
      right = rightData.subarray(i, i + maxSamples)
      mp3buf = mp3enc.encodeBuffer(left, right)
    } else {
      mp3buf = mp3enc.encodeBuffer(left)
    }

    if (mp3buf.length > 0) {
      buffer.push(mp3buf)
    }
  }

  const enc = mp3enc.flush()

  if (enc.length > 0) {
    buffer.push(enc)
  }

  let blob = new Blob(buffer, {
    type: 'audio/mp3',
  })
  return blob
}

获取 Gop 大小(关键帧间隔)

javascript
;<script src='https://j.weizan.cn/zhibo/js/jquery-2.1.4.min.js'></script>

$.ajax({
  url: video_src, // 视频播放地址
  dataType: 'TEXT',
  success: (res) => {
    // 解析 m3u8
    var m3u8list = res.replace(/\n/g, '<br>').split('<br>')
    // 获取 Gop 大小
    var gopSize = parseInt(m3u8list[3].split(':').pop())
    console.log('gop size:' + gopSize)
  },
})