Non-realtime MediaRecorder

by akre54

HTML

<button id="start">Start</button>
<canvas id="canvas" height="200" width="200"></canvas>
<video id="video" controls height="200" width="200"></video>

JavaScript

const canvas = document.querySelector('#canvas')
const startBtn = document.querySelector('#start')
const video = document.querySelector('#video')

const stream = canvas.captureStream(0)
const mr = new MediaRecorder(stream, { mimeType: 'video/webm;codecs=vp9', videoBitsPerSecond: 2500000 })
const [track] = stream.getVideoTracks()

let chunks
mr.addEventListener('dataavailable', e => chunks.push(e.data))

function start() {
	chunks = []
  mr.start(0)
  
  const totalTime = 6
  const stepSize = 1 / 24

  let frame = 0
  async function loop () {
    const t = frame * stepSize
    await render(t)
	  await captureFrame()
    frame++
    if (t < totalTime) {
    	requestAnimationFrame(loop)
    } else {
	    finish()
    }
  }
  
  requestAnimationFrame(loop)
}

startBtn.addEventListener('click', start)

async function captureFrame() {
  console.log('chunks length', chunks.length)
  // mr.resume()
  track.requestFrame()
  mr.requestData()
  // return new Promise(async (resolve) => {
  //   mr.pause()
  //   resolve()
  // })
}

async function finish() {
  await mr.stop()
  const url = URL.createObjectURL(new Blob(chunks, {type: 'video/webm'}))
  video.src = url
  video.play()
  console.log('finished', chunks, url)
}

async function render(t) {
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  ctx.font = 'bold 24px serif'
  ctx.fillText(`Val: ${Math.round(t * 10) / 10}`, 50, 50)

  // Simulate an expensive draw call
  return new Promise((resolve) => {
    setTimeout(resolve, 40)
  })
}