-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
95 lines (93 loc) · 2.73 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const canvasElement = document.getElementById("output_canvas");
const canvasCtx = canvasElement.getContext("2d");
const chara = new Image();
chara.src = "./sample.jpeg";
function onResults(results) {
canvasCtx.save();
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.drawImage(
results.segmentationMask,
0,
0,
canvasElement.width,
canvasElement.height
);
canvasCtx.globalCompositeOperation = "source-in";
canvasCtx.drawImage(
results.image,
0,
0,
canvasElement.width,
canvasElement.height
);
canvasCtx.globalCompositeOperation = "destination-atop";
canvasCtx.drawImage(chara, 0, 0, canvasElement.width, canvasElement.height);
canvasCtx.restore();
results.segmentationMask.close();
results.image.close();
}
const selfieSegmentation = new SelfieSegmentation({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation/${file}`;
},
});
selfieSegmentation.setOptions({
modelSelection: 1,
});
selfieSegmentation.onResults(onResults);
(async function () {
const localMediaStream = await navigator.mediaDevices.getUserMedia({
video: {
width: 1080,
height: 720,
frameRate: 15,
},
audio: false,
});
const processor = new MediaStreamTrackProcessor(
localMediaStream.getVideoTracks()[0]
);
const writable = new WritableStream({
start() {
console.log("WritableStream started");
},
async write(videoFrame) {
const imageBitmap = await createImageBitmap(videoFrame);
await selfieSegmentation.send({ image: imageBitmap });
imageBitmap.close();
videoFrame.close();
},
stop() {
console.log("WritableStream stopped");
},
});
processor.readable.pipeTo(writable);
// ストリームの取得
const segmentedLocalMediaStream = canvasElement.captureStream();
const peer = new Peer({
key: "<YOUR API KEY>",
debug: 3,
});
peer.on("open", () => {
document.getElementById("my-id").textContent = peer.id;
});
peer.on("call", (mediaConnection) => {
mediaConnection.answer(segmentedLocalMediaStream);
setEventListener(mediaConnection);
});
// 発信処理
document.getElementById("make-call").onclick = () => {
const theirID = document.getElementById("their-id").value;
const mediaConnection = peer.call(theirID, segmentedLocalMediaStream);
setEventListener(mediaConnection);
};
// イベントリスナを設置する関数
const setEventListener = (mediaConnection) => {
mediaConnection.on("stream", (stream) => {
// video要素にカメラ映像をセットして再生
const videoElm = document.getElementById("their-video");
videoElm.srcObject = stream;
videoElm.play();
});
};
})();