curriculum/challenges/english/blocks/lecture-working-with-audio-and-video/6733d852175df50937f06061.md
Instead of playing audio and video, you may sometimes want to capture audio or video. The Media Capture and Streams API, or the MediaStream API, allows you to do this.
In order to use the API, however, you need to create the MediaStream object. You could do this with the constructor, but it would not be tied to the user's hardware. Instead, the mediaDevices property of the global navigator object has a getUserMedia() method for you to use.
This method accepts a single constraints object which defines the type of media you want to receive. This object has an audio and video property, reflecting audio and video streams. These properties can be false, if you do not want to receive that type of stream, true if you do, or objects defining additional constraints.
For example, you can require a specific resolution of video output:
window.navigator.mediaDevices.getUserMedia({
audio: true,
video: {
width: {
min: 1280,
ideal: 1920,
max: 3840
},
height: {
min: 720,
ideal: 1080,
max: 2160
}
}
});
This constraint object specifies minimum and maximum resolutions for the video feed. The ideal property specifies the resolution you'd most like to have – and the stream will provide the resolution closest to your ideal.
Once you've created your MediaStream (assuming the user approves the automated request to access their hardware), you can use the stream data however you need.
Note that getUserMedia() returns a Promise, which means you will either need a callback function to consume the stream, or use async/await syntax. You will learn more about Promises and asynchronous programming in future lessons.
Here's a basic example which renders the user's webcam feed to the page.
const video = document.querySelector("video");
const stream =
await window.navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
await video.play();
It is worth noting that this API does not offer access to screen capture. You'll learn about that API in the next lesson.
Which method is used to access the user's media devices?
createMediaStream()
This method accesses the user's media devices.
getMediaDevices()
This method accesses the user's media devices.
getUserMedia()
captureStream()
This method accesses the user's media devices.
3
In the constraints object for video, what does the ideal property represent?
The minimum acceptable resolution.
Think about what the word ideal means.
The maximum possible resolution.
Think about what the word ideal means.
The preferred resolution.
The default resolution if no other constraints are met.
Think about what the word ideal means.
3
What is returned by the getUserMedia() method?
A MediaStream object.
The getUserMedia() method is asynchronous.
A constraints object.
The getUserMedia() method is asynchronous.
A Promise.
A video element.
The getUserMedia() method is asynchronous.
3