I have the following code for the web component which should start video streaming of the cam when the user clicks on the button
class WebStream extends LitElement {
constructor(){
super();
this.attachShadow({ mode: 'open' });
}
render() {
return html`
<button @click="${this.startStreaming}">start streaming</button>
`;
}
startStreaming() {
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
}).then(function(mediaStream){
const shadowRoot = this;
let shadow = document.createElement("div")
shadowRoot.appendChild(shadow);
this.video = document.createElement('video');
shadow.appendChild(this.video);
this.video.srcObject = mediaStream
console.log(mediaStream)
this.video.setAttribute("width", "320");
this.video.setAttribute("height", "240");
this.video.play()
}.bind(this))
.catch(function(error){
console.log(error)
})
}
}
with this code it starts streaming, and I can listen the audio but on the browser I cant see anything
CodePudding user response:
I tried to run your code and the catch block logged DOMException: Permission denied
. I googled the message and this stackoverflow question maybe is your case. Hope it help.
CodePudding user response:
In native code its:
But it won't run as SO Snippet, so see the JSFiddle: https://jsfiddle.net/WebComponents/btqvynd3/
<web-cam></web-cam>
<script>
customElements.define("web-cam", class extends HTMLElement {
constructor() {
super().attachShadow({mode:'open'}).innerHTML=`<video></video>`;
}
connectedCallback() {
navigator.mediaDevices.getUserMedia({
audio: true,
video: { width: 320, height: 240 },
}).then((mediaStream) =>{
this.video = this.shadowRoot.querySelector('video');
this.video.srcObject = mediaStream;
this.video.play();
this.onclick = (evt) => {
this.video.pause();
}
})
.catch(function(error) {
console.log(error)
})
}
})
</script>
Note: the error in your code is a 'this' reference to lightDOM, NOT to the Components shadowRoot
const shadowRoot = this;
let shadow = document.createElement("div")
shadowRoot.appendChild(shadow);