2

I'm trying to learn more about streaming webcams and i'm stuck at stopping the video I hope someone can help me with stopping the video

var videoDiv = $("#video"),
 vendorUrl = window.URL || window.webkitURL;
 navigator.getMedia =  navigator.getUserMedia ||
       navigator.webkitGetUserMedia ||
       navigator.mozGetUserMedia ||
       navigator.oGetUserMedia ||
       navigator.msGetUserMedia;

function captureWebcam(video, audio){
 navigator.getMedia({
  video: video,
  audio: audio
 }, function(stream){
  localStream = stream;
  videoDiv.attr("src", vendorUrl.createObjectURL(localStream))
 }, function(error){
  // An error occured
  // error.code
  console.log(error)
 }); 
}  
$("#stop").on("click", function(){

 videoDiv.attr("src", "") 
 //captureWebcam(false, false)
    // Stop the video
}); 
$("#start").on("click", function(){
 captureWebcam(true, false)
});
<video id="video" width="400" height="300"></video>
<button id="start">START!</button>
<button id="stop">STOP!</button>
I NA
  • 137
  • 1
  • 6
  • Possible duplicate of [Stop/Close webcam which is opened by navigator.getUserMedia](http://stackoverflow.com/questions/11642926/stop-close-webcam-which-is-opened-by-navigator-getusermedia) – jcaron Dec 04 '15 at 10:41

1 Answers1

6

You need to use getTrack() to be able stop the stream.

var videoDiv = document.getElementById("video"),
    vendorUrl = window.URL || window.webkitURL;
    navigator.getMedia =    navigator.getUserMedia ||
                            navigator.webkitGetUserMedia ||
                            navigator.mozGetUserMedia ||
                            navigator.oGetUserMedia ||
                            navigator.msGetUserMedia;

var MediaStream;
function captureWebcam(video, audio){
    navigator.getMedia({
        video: video,
        audio: audio
    }, function(stream){
        videoDiv.src = vendorUrl.createObjectURL(stream);
        MediaStream = stream.getTracks()[0]; // create the stream tracker
    }, function(error){
        // An error occured
        // error.code
        console.log(error)
    }); 
}       
$("#stop").on("click", function(){
   // Stop the tracked stream
   MediaStream.stop()
}); 
$("#start").on("click", function(){
    captureWebcam(true, false)
});

Also fiddle it for you to check it out

Hakan Kose
  • 1,649
  • 9
  • 16