The MediaDevices interface allows accessing a user's webcam and microphone, as well as allowing screen sharing. It requires a secure connection and prompts the user for permission after which the output - aka MediaStream - can be used within your application. We'll specifically be learning how to use getUserMedia() to stream a user's webcam video and compose it with an SVG inside of HTML canvas to generate a screenshot, like mine! Requesting and displaying a video media stream # There are a few essential parts of requesting a media stream, as in a user's video source like a webcam and/or an audio source like from a microphone. The starting point is a call to navigator.mediaDevices.getUserMedia() along with an object holding the requested "constraints." The constraints include which types of media streams you would like - video and or audio - and other features like preferred dimensions. For the purposes of our holiday card, we're also going to request the front-facing camera as the preferred. A Promise is returned from getUserMedia() along with the media stream if successful. The media stream can contain multiple "tracks" for each of audio and video sources. We can wrap up the minimal required pieces as follows: const handleSuccess = ( stream ) => { const video = document . querySelector ( "video" ) ; window . stream = stream ; video . srcObject = stream ; } ; const handleError = ( error ) => { console . error ( "Error: " , error ) ; } ; const startWebcam = ( ) => { navigator . mediaDevices . getUserMedia ( { video : true } ) . then ( handleSuccess ) . catch ( handleError ) ; } ; In your HTML you would have an empty
Comments
Sign in to join the conversation.
No comments yet. Be the first.