Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Last active April 20, 2020 23:04
Show Gist options
  • Save m3g4p0p/a820071780407874f35b6c843e1906b9 to your computer and use it in GitHub Desktop.
Save m3g4p0p/a820071780407874f35b6c843e1906b9 to your computer and use it in GitHub Desktop.
Record a video with the web cam and upload it to the server
const video = document.querySelector('video')
const start = document.querySelector('.start')
const stop = document.querySelector('.stop')
const upload = document.querySelector('.upload')
const initRecorder = stream => {
const recorder = new MediaRecorder(stream)
let blob
video.srcObject = stream
start.removeAttribute('disabled')
video.addEventListener('loadedmetadata', () => {
video.play()
})
recorder.addEventListener('dataavailable', ({ data }) => {
video.srcObject = null
video.src = URL.createObjectURL(data)
// Create a blob from the data for upload
blob = new Blob([data], { type: 'video/webm' })
})
start.addEventListener('click', () => {
stop.removeAttribute('disabled')
recorder.start()
})
stop.addEventListener('click', () => {
upload.removeAttribute('disabled')
recorder.stop()
})
// Upload the video blob as form data
upload.addEventListener('click', () => {
const body = new FormData()
body.append('myvideo', blob)
fetch('upload.php', { method: 'POST', body })
.then(() => console.log('Success!'))
.catch(console.error)
})
}
navigator
.mediaDevices
.getUserMedia({ video: true })
.then(initRecorder)
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment