Skip to content

Commit 5a8f7bd

Browse files
committed
feat: 更新 open close 方法实现逻辑
1 parent 5e4ee67 commit 5a8f7bd

File tree

1 file changed

+40
-16
lines changed
  • src/BootstrapBlazor/wwwroot/modules

1 file changed

+40
-16
lines changed

src/BootstrapBlazor/wwwroot/modules/media.js

Lines changed: 40 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,33 +16,57 @@ export async function enumerateDevices() {
1616
export async function open(options) {
1717
const constrains = {
1818
video: {
19-
facingMode: { exact: options.facingMode || "environment" },
2019
deviceId: options.deviceId ? { exact: options.deviceId } : null,
20+
facingMode: { ideal: options.facingMode || "environment" }
2121
},
2222
audio: false
2323
}
24-
const video = document.querySelector(options.videoSelector);
25-
if (video) {
26-
const stream = await navigator.mediaDevices.getUserMedia(constrains);
27-
video.srcObject = stream;
24+
25+
const { videoSelector, width, height } = options;
26+
if (width) {
27+
constrains.video.width = { ideal: width };
28+
}
29+
if (height) {
30+
constrains.video.height = { ideal: height };
31+
}
32+
const stream = await navigator.mediaDevices.getUserMedia(constrains);
33+
const media = registerBootstrapBlazorModule("MediaDevices");
34+
media.stream = stream;
35+
36+
if (videoSelector) {
37+
const video = document.querySelector(videoSelector);
38+
if (video) {
39+
video.srcObject = stream;
40+
}
2841
}
2942
}
3043

3144
export async function close(videoSelector) {
32-
const video = document.querySelector(videoSelector);
33-
if (video) {
34-
video.pause();
35-
const stream = video.srcObject;
36-
if (stream) {
37-
const tracks = stream.getTracks();
38-
39-
tracks.forEach(track => {
40-
track.stop();
41-
});
42-
45+
if (videoSelector) {
46+
const video = document.querySelector(videoSelector);
47+
if (video) {
48+
video.pause();
49+
const stream = video.srcObject;
50+
closeStream(stream);
4351
video.srcObject = null;
4452
}
4553
}
54+
const media = registerBootstrapBlazorModule("MediaDevices");
55+
const { stream } = media;
56+
if (stream && stream.active) {
57+
closeStream(stream);
58+
}
59+
media.stream = null;
60+
}
61+
62+
const closeStream = stream => {
63+
if (stream) {
64+
const tracks = stream.getTracks();
65+
66+
tracks.forEach(track => {
67+
track.stop();
68+
});
69+
}
4670
}
4771

4872
export async function capture(videoSelector) {

0 commit comments

Comments
 (0)