4

I'm trying to get Chrome's getUserMedia to work on my localhost.

My index.php file is:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/script.js"></script>
        <title></title>
    </head>
    <body>
<video id="MediaStreamVideo" autoplay=""></video>    
    </body>
</html>

My script.js file is:

var stream;
var video = document.getElementById('MediaStreamVideo'); 
navigator.webkitGetUserMedia(
    {video: true, audio: true}, // Options
    function(localMediaStream) { // Success
        stream = localMediaStream;
        video.src = window.webkitURL.createObjectURL(stream);
    },
    function(err) { // Failure
        alert('getUserMedia failed: Code ' + err.code);
    }
);

Chrome asks me to allow using the camera and microphone (which I accept), but then nothing happens.

It works fine on jsfidde

Any ideas?

Tomi Seus
  • 1,131
  • 2
  • 13
  • 28

3 Answers3

2

The problem should be with the order in which the script is getting executed. The video element 'MediaStreamVideo' will not be available when the script was getting executed.

Its always a good practice to load the scripts at the end. Also, wrap the code inside a function and execute it onload.

Varunkumar Nagarajan
  • 1,807
  • 1
  • 24
  • 43
  • Is it good practice to include scripts at the end or inline? I've always done it in the head section. – taco Feb 01 '13 at 21:45
  • Its a good practice to defer loading of resources (scripts) till the initial page is loaded. Put all your scripts at the end of the body. – Varunkumar Nagarajan Feb 02 '13 at 08:03
  • Thanks for your response. Either at the end of the body, or use [jQuery's .ready()](http://api.jquery.com/ready/) function - that will suffice, correct? From what I've read, it accomplishes the same thing. – taco Feb 06 '13 at 18:25
  • 1
    No. Deferring the loading of script is different from the script execution. Loading the scripts at the end of the body makes sure that the other parts of the page is parsed by the browser before trying to load the scripts. jquery.ready() is more like a starting point of your application after the scripts are loaded. – Varunkumar Nagarajan Feb 06 '13 at 18:29
0

If you are in Chrome, and using a file:/// URL, then you need to call Chrome with the command line argument of --allow-file-access-from-files.

You may want to check out this SO Q&A.

Community
  • 1
  • 1
Clay Bridges
  • 11,602
  • 10
  • 68
  • 118
0

Simply try:

var stream;
var video = document.getElementById('MediaStreamVideo'); 
navigator.webkitGetUserMedia(
    {video: true, audio: true}, // Options
    function(localMediaStream) { // Success
        stream = localMediaStream;
        //video.src = window.webkitURL.createObjectURL(stream);
        video.srcObject = stream;
   },
   function(err) { // Failure
      alert('getUserMedia failed: Code ' + err.code);
   }
);
Mike
  • 493
  • 5
  • 14