Created
March 31, 2017 05:47
-
-
Save voltrevo/027b598923663edd545396c8dcc446dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const createElement = (tag, styles = {}) => { | |
const el = document.createElement(tag); | |
for (const [key, value] of Object.entries(styles)) { | |
el.style[key] = value; | |
} | |
return el; | |
}; | |
function event(obj, evtName) { | |
const on = ( | |
obj.addEventListener || | |
obj.addListener || | |
obj.on | |
).bind(obj); | |
const off = ( | |
obj.removeEventListener || | |
obj.removeListener || | |
obj.off | |
).bind(obj); | |
let handler; | |
return new Promise(resolve => on(evtName, handler = (evt) => { | |
off(evtName, handler); | |
resolve(evt); | |
})); | |
} | |
async function run() { | |
await event(window, 'load'); | |
const constraintsInput = createElement('textarea', { | |
width: '100%', | |
height: '50vh', | |
fontFamily: 'monospace', | |
}); | |
constraintsInput.textContent = JSON.stringify({ | |
audio: true, | |
video: true, | |
}, null, 2); | |
document.body.appendChild(constraintsInput); | |
const btn = createElement('button', { | |
width: '100%', | |
}); | |
btn.textContent = 'getUserMedia'; | |
document.body.appendChild(btn); | |
document.addEventListener('keydown', (evt) => { | |
if (evt.metaKey && evt.key === 'Enter') { | |
btn.click(); | |
} | |
}); | |
const output = document.createElement('div'); | |
document.body.appendChild(output); | |
while (true) { | |
try { | |
await event(btn, 'click'); | |
output.innerHTML = ''; | |
const constraints = JSON.parse(constraintsInput.value); | |
const stream = await navigator.mediaDevices.getUserMedia(constraints); | |
window.stream = stream; | |
event(btn, 'click').then(() => stream.getTracks().forEach(track => track.stop())); | |
const vid = document.createElement('video'); | |
output.appendChild(vid); | |
vid.srcObject = stream; | |
await vid.play(); | |
} catch(e) { | |
const pre = document.createElement('pre'); | |
pre.textContent = e.stack || e.message; | |
output.appendChild(pre); | |
} | |
} | |
} | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment