Search code examples
javascriptandroidvideowebrtcgetusermedia

Calling getUserMedia with new constraints causes black screen (MediaStream.ended=true)


On my nexus4 (Android 4.4.4) I am trying to switch between 'user' facing camera and 'environment' facing camera.

Accessing either one directly works. Switching between them bij making another call to navigator.getUserMedia() setting new constraints fails. The failure results in a black screen video & MediaStream.ended=true.

Why is MediaStream.ended=true on my second call to getUserMedia?

In my view I dynamically create buttons for the number of video sources. Two in this case. Clicking the buttons will call camera.getUserMedia() and passes in a media source:

    camera.getUserMedia = function(source){
        var constraints = {
            video: true,
            audio: false
        };
        if(source){
            constraints.video = {optional: [{
                sourceId: source.id
            }]};
        }
        navigator.getMedia(
            constraints,
            function(stream) {
                var vendorURL = window.URL || window.webkitURL;
                video.src = vendorURL.createObjectURL(stream);
                video.play();
                streaming = true;
            },
            function(err) {
                ...
            }
        );
    };

enter image description here


Solution

  • I have solved this problem by storing the stream on the camera object and then before binding the stream to the video element I will call stop on it. Not really sure what is exactly happening though (maybe somebody can add the explanation in the comments).

        camera.getUserMedia = function(source){
            if(camera.stream){
                camera.stream.stop();
            }
            ...
            navigator.getMedia(
                constraints,
                function(stream) {
                    camera.stream = stream;
                    ...
                },
                function(err) {
                    ...
                }
            );
        };