1

I have a problem. When I click the camera button (there is the code below) I can open the camera, but how can I turn the camera off when I click the same button.

A part of my code.

button : <a type="button" onclick="cameraOff()" name="button" id="button"> <i class="fas fa-video fa-2x cam-btn"></i> </a>

<video id="video" width="640" height="480" autoplay></video>

<script>
    function cameraOff() {

        var video = document.getElementById('video');
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({
                video: true
            }).then(function(stream) {
                video.srcObject = stream;
                video.play();
            });
        }
    }
</script>
Baris
  • 29
  • 8

2 Answers2

1

Check this sandbox https://codesandbox.io/s/video-onoff-js-zyrxh?file=/index.html

function cameraoff() {
        const stream = videoElem.srcObject;
        if (stream) {
          const tracks = stream.getTracks();

          tracks.forEach(function (track) {
            track.stop();
          });

          videoElem.srcObject = null;
       }
  }
MANOJ MUKHERJEE
  • 201
  • 2
  • 12
0

replace the video.srcObject = stream; video.play(); with video.srcObject={}; video.pause(); stream.stop(); reference to my answer

Skerrepy
  • 354
  • 4
  • 6
  • If you have already answered this elsewhere, why not flag the question as a duplicate? – evolutionxbox May 04 '21 at 12:12
  • That's good then, but why did you answer as well? – evolutionxbox May 04 '21 at 12:14
  • @evolutionxbox tried to answer his question while the process completes :) i even referenced the other answer but you are right should of just flagged it. – Skerrepy May 04 '21 at 12:16
  • I looked at the page on the link but I think the camera is already on and there is a button to turn it off. Imagine being able to turn your camera on at one button and turn it off when you click it again.@evolutionxbox – Baris May 04 '21 at 12:17
  • @vikbaris [How to toggle on/off buttons](https://stackoverflow.com/questions/37241473/toggle-on-off-buttons-in-javascript/37241526) – Shashank Gb May 04 '21 at 12:19