-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo-ws.js
83 lines (72 loc) · 3.23 KB
/
video-ws.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
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** -------------------------------------------------------------------------*/
import { MediaStream } from './mediastream.js';
const scriptPath = new URL(import.meta.url).pathname;
class VideoWsElement extends HTMLElement {
static observedAttributes = ["url"];
constructor() {
super();
this.shadowDOM = this.attachShadow({mode: 'open'});
this.shadowDOM.innerHTML = `
<link rel="stylesheet" href="${scriptPath.substring(0, scriptPath.lastIndexOf('/'))}/video-ws.css">
<div class="videoContent">
<video id="video" muted playsinline controls preload="none"></video>
<div id="spinner" class="loading"></div>
</div>`;
this.audioContext = new AudioContext();
const canvas = document.createElement("canvas");
this.stream = canvas.captureStream();
const audioTrack = this.audioContext.createMediaStreamDestination().stream.getAudioTracks()[0];
this.mediaStream = new MediaStream(canvas, this.audioContext, (loaded) => {
if (loaded) {
this.shadowDOM.getElementById("spinner").classList.remove("loading");
} else {
this.shadowDOM.getElementById("spinner").classList.add("loading");
}
}, (loaded) => {
if (loaded) {
this.stream.addTrack(audioTrack);
this.audioContext.resume();
} else {
this.stream.removeTrack(audioTrack);
this.audioContext.suspend();
}
}
);
}
connectedCallback() {
console.log("connectedCallback");
const video = this.shadowDOM.getElementById("video");
video.srcObject = this.stream;
video.addEventListener('play', () => this.audioContext.resume());
video.addEventListener('pause', () => this.audioContext.suspend());
video.addEventListener('volumechange', () => this.mediaStream.setVolume(video.muted ? 0 : video.volume));
this.audioContext.onstatechange = () => {
switch(this.audioContext.state) {
case 'suspended':
video.muted = true;
break;
case 'running':
video.muted = false;
break;
}
};
video.play();
}
disconnectedCallback() {
console.log("disconnectedCallback");
this.mediaStream.close();
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`Attribute ${name} has changed.`);
if (name === "url" && oldValue !== newValue) {
this.shadowDOM.getElementById("spinner").classList.add("loading");
this.mediaStream.connect(newValue);
}
}
}
customElements.define("video-ws", VideoWsElement);