Search code examples
javascriptgoogle-chrome-extensionwebcam

Chrome Extension - How to access webcam and Audio at intervals?


I have a chrome extension I am using that I want to integrate with my webcam to do some funky computer vision and audio ML stuff.

usuauly i'd do something liek this,

for audio,

<audio id="player" controls></audio>
<script>
  const player = document.getElementById('player');

  const handleSuccess = function(stream) {
    if (window.URL) {
      player.srcObject = stream;
    } else {
      player.src = stream;
    }
  };

  navigator.mediaDevices.getUserMedia({ audio: true, video: false })
      .then(handleSuccess);
</script>

for webcam

<video autoplay></video>

<script>
const constraints = {
  video: true
};

const video = document.querySelector('video');

navigator.mediaDevices.getUserMedia(constraints).
  then((stream) => {video.srcObject = stream});
</script>

With a chrome extension, would the best pathway be to use the background.js file - I am struggling to find any documentation or information about how I could do it with that.

Thanks in advance!


Solution

  • You can create an option page (HTML file which lives in extension directory) and have camera/audio permissions granted there once. after this, you can use these APIs directly in background scripts

    Here is the example of doing so.