Request a media stream with the specified constraints. This is a class method that requests access to media devices matching the given `audio` and `video` constraints. The browser will prompt the user for permission if needed and return a `MediaStream` object that
(cls, audio=False, video=True)
| 118 | |
| 119 | @classmethod |
| 120 | async def request_stream(cls, audio=False, video=True): |
| 121 | """ |
| 122 | Request a media stream with the specified constraints. |
| 123 | |
| 124 | This is a class method that requests access to media devices matching |
| 125 | the given `audio` and `video` constraints. The browser will prompt the |
| 126 | user for permission if needed and return a `MediaStream` object that |
| 127 | can be assigned to video/audio elements. |
| 128 | |
| 129 | Simple boolean constraints for `audio` and `video` can be used to |
| 130 | request default devices. More complex constraints can be specified as |
| 131 | dictionaries conforming to |
| 132 | [the MediaTrackConstraints interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints). |
| 133 | |
| 134 | ```python |
| 135 | from pyscript import document |
| 136 | from pyscript.media import Device |
| 137 | |
| 138 | |
| 139 | # Get default video stream. |
| 140 | stream = await Device.request_stream() |
| 141 | |
| 142 | # Get stream with specific constraints. |
| 143 | stream = await Device.request_stream( |
| 144 | video={"width": 1920, "height": 1080} |
| 145 | ) |
| 146 | |
| 147 | # Get audio and video. |
| 148 | stream = await Device.request_stream(audio=True, video=True) |
| 149 | |
| 150 | # Use the stream. |
| 151 | video_el = document.getElementById("camera") |
| 152 | video_el.srcObject = stream |
| 153 | ``` |
| 154 | |
| 155 | This method will trigger a browser permission dialog on first use. |
| 156 | """ |
| 157 | options = {} |
| 158 | if isinstance(audio, bool): |
| 159 | options["audio"] = audio |
| 160 | elif isinstance(audio, dict): |
| 161 | # audio is a dict of constraints (sampleRate, echoCancellation etc...). |
| 162 | options["audio"] = audio |
| 163 | if isinstance(video, bool): |
| 164 | options["video"] = video |
| 165 | elif isinstance(video, dict): |
| 166 | # video is a dict of constraints (width, height etc...). |
| 167 | options["video"] = video |
| 168 | return await window.navigator.mediaDevices.getUserMedia(to_js(options)) |
| 169 | |
| 170 | @classmethod |
| 171 | async def load(cls, audio=False, video=True): |