I am trying to create a voice-controlled website. What I exactly plan to do is say 'hello' to trigger the button 'Open WebCam'. I am using Annyang for processing my voice commands and simple javascript selectors to open the webcam. But even though, these two work fine separately but every time I try to integrate these two for the final result, I get stuck.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Voice Control</title>
</head>
<style>
div {
width: 500px;
height: 400px;
border: 2px solid black;
position: relative;
}
video {
width: 500px;
height: 400px;
object-fit: cover;
}
</style>
<body>
<center>
<div>
<video id="vid"></video>
</div>
<br />
<button id="but" autoplay>
Open WebCam
</button>
</center>
</body>
<script src="//cdnjs.cloudflare.com/ajax/libs/annyang/2.6.1/annyang.min.js"></script>
<script>
if(annyang) {
var commands = {
'hello': function() {
document.addEventListener("DOMContentLoaded", () => {
var but = document.getElementById("but");
var video = document.getElementById("vid");
var mediaDevices = navigator.mediaDevices;
vid.muted = true;
but.addEventListener("click", () => {
// Accessing the user camera and video.
mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then((stream) => {
// Changing the source of video to current stream.
video.srcObject = stream;
video.addEventListener("loadedmetadata", () => {
video.play();
});
})
.catch(alert);
});
});
}
};
annyang.addCommands(commands);
annyang.start();
}
</script>
</html>