I NA
I NA

Reputation: 137

Stop video with getUserMedia

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>

Upvotes: 2

Views: 6471

Answers (1)

Hakan Kose
Hakan Kose

Reputation: 1656

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

Upvotes: 6

Related Questions