Help with changing auto record to manual record

This script for recording webcam video launches automatically into recording upon page refresh. Can you suggest a way to help me change this into manual start, instead of automatic? Any help will be appreciated.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <style>
            video {
              max-width: 100%;
              border: 5px solid yellow;
              border-radius: 9px;
            }
            body {
              background: ffffff;
            }
            h1 {
              color: #800000;
            }
        </style>
    </head>

    <body>
        <h1 id="header">RecordRTC Upload to PHP</h1>
        <video id="your-video-id" controls="" autoplay=""></video>

        <script type="text/javascript">
            // capture camera and/or microphone
            navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function(camera) {
                // preview camera during recording
                document.getElementById('your-video-id').muted = false;
                setSrcObject(camera, document.getElementById('your-video-id'));
                // recording configuration/hints/parameters
                var recordingHints = {
                    type: 'video'
                };
                // initiating the recorder
                var recorder = RecordRTC(camera, recordingHints);
                // starting recording here
                recorder.startRecording();
                // auto stop recording after 5 seconds
                var milliSeconds = 5 * 1000;
                setTimeout(function() {
                    // stop recording
                    recorder.stopRecording(function() {

                        // get recorded blob
                        var blob = recorder.getBlob();
                        // generating a random file name
                        var fileName = getFileName('webm');
                        // we need to upload "File" --- not "Blob"
                        var fileObject = new File([blob], fileName, {
                            type: 'video/webm'
                        });

                        uploadToPHPServer(fileObject, function(response, fileDownloadURL) {
                            if(response !== 'ended') {
                                document.getElementById('header').innerHTML = response; // upload progress
                                return;
                            }
                            document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL + '" target="_blank">' + fileDownloadURL + '</a>';
                            alert('Successfully uploaded recorded blob.');
                            // preview uploaded file
                            document.getElementById('your-video-id').src = fileDownloadURL;
                            // open uploaded file in a new tab
                            window.open(fileDownloadURL);
                        });
                        // release camera
                        document.getElementById('your-video-id').srcObject = document.getElementById('your-video-id').src = null;
                        camera.getTracks().forEach(function(track) {
                            track.stop();
                        });
                    });
                }, milliSeconds);
            });
            function uploadToPHPServer(blob, callback) {
                // create FormData
                var formData = new FormData();
                formData.append('video-filename', blob.name);
                formData.append('video-blob', blob);
                callback('Uploading recorded-file to server.');
                makeXMLHttpRequest('save.php', formData, function(progress) {
                    if (progress !== 'upload-ended') {
                        callback(progress);
                        return;
                    }
                    var initialURL = '../uploads/' + blob.name;
                    callback('ended', initialURL);
                });
            }
            function makeXMLHttpRequest(url, data, callback) {
                var request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    if (request.readyState == 4 && request.status == 200) {
                        if (request.responseText === 'success') {
                            callback('upload-ended');
                            return;
                        }
                        alert(request.responseText);
                        return;
                    }
                };
                request.upload.onloadstart = function() {
                    callback('PHP upload started...');
                };
                request.upload.onprogress = function(event) {
                    callback('PHP upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
                };
                request.upload.onload = function() {
                    callback('progress-about-to-end');
                };
                request.upload.onload = function() {
                    callback('PHP upload ended. Getting file URL.');
                };
                request.upload.onerror = function(error) {
                    callback('PHP upload failed.');
                };
                request.upload.onabort = function(error) {
                    callback('PHP upload aborted.');
                };
                request.open('POST', url);
                request.send(data);
            }
            // this function is used to generate random file name
            function getFileName(fileExtension) {
                var d = new Date();
                var year = d.getUTCFullYear();
                var month = d.getUTCMonth();
                var date = d.getUTCDate();
                return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
            }
            function getRandomString() {
                if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                    var a = window.crypto.getRandomValues(new Uint32Array(3)),
                        token = '';
                    for (var i = 0, l = a.length; i < l; i++) {
                        token += a[i].toString(36);
                    }
                    return token;
                } else {
                    return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
                }
            }
        </script>
    </body>
</html>

Is it anything to do with this section of code?

// starting recording here
recorder.startRecording();

Hi, you could simply move the code which is responsible for starting recording into its own function and call that when you’re ready.

It’s basically this block:

// capture camera and/or microphone
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).
  then(function(camera) {
   ...
   });

So you could do:

function startRecording(){
  navigator.mediaDevices.getUserMedia({ video: true, audio: true }).
    then(function(camera) {
     ...
   });
}}

and then call that function from wherever you like.

1 Like

Thanks for your reply.
Can you give me a code example of what you mean when you say “call that function from wherever you like”?
Much thanks again

Sure.

myButton.addEventListener("click", startRecording, false);

Thanks again for your help, however, I’m obviously doing something wrong. I’ve added your first code to line 27, then line 39, and added a button on line 145, but no success with manually starting the recording. Any additional help will be appreciated. Here’s the revised code:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
        <style>
            video {
              max-width: 100%;
              border: 5px solid #800000;
              border-radius: 9px;
            }
            body {
              background: e5e5e5;
            }
            h1 {
              color: black;
            }
        </style>
    </head>

    <body>
        <h1 id="header">RecordRTC</h1>
        <video id="your-video-id" controls="" autoplay=""></video>

        <script type="text/javascript">
            // capture camera and/or microphone
            **function startRecording(){**
**			  navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function(camera) {**
                // preview camera during recording
                document.getElementById('your-video-id').muted = false;
                setSrcObject(camera, document.getElementById('your-video-id'));
                // recording configuration/hints/parameters
                   });
}}

                // initiating the recorder
                var recorder = RecordRTC(camera, recordingHints);
                // starting recording here
                **myButton.addEventListener("click", startRecording, true);**
                recorder.startRecording();
                // auto stop recording after 5 seconds
                var milliSeconds = 5 * 1000;
                setTimeout(function() {
                    // stop recording
                    recorder.stopRecording(function() {

                        // get recorded blob
                        var blob = recorder.getBlob();
                        // generating a random file name
                        var fileName = getFileName('webm');
                        // we need to upload "File" --- not "Blob"
                        var fileObject = new File([blob], fileName, {
                            type: 'video/webm'
                        });

                        uploadToPHPServer(fileObject, function(response, fileDownloadURL) {
                            if(response !== 'ended') {
                                document.getElementById('header').innerHTML = response; // upload progress
                                return;
                            }
                            document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL + '" target="_blank">' + fileDownloadURL + '</a>';
                            alert('Successfully uploaded recorded blob.');
                            // preview uploaded file
                            document.getElementById('your-video-id').src = fileDownloadURL;
                            // open uploaded file in a new tab
                            window.open(fileDownloadURL);
                        });
                        // release camera
                        document.getElementById('your-video-id').srcObject = document.getElementById('your-video-id').src = null;
                        camera.getTracks().forEach(function(track) {
                            track.stop();
                        });
                    });
                }, milliSeconds);
            });
            function uploadToPHPServer(blob, callback) {
                // create FormData
                var formData = new FormData();
                formData.append('video-filename', blob.name);
                formData.append('video-blob', blob);
                callback('Uploading recorded-file to server.');
                makeXMLHttpRequest('save.php', formData, function(progress) {
                    if (progress !== 'upload-ended') {
                        callback(progress);
                        return;
                    }
                    var initialURL = '/uploads/' + blob.name;
                    callback('ended', initialURL);
                });
            }
            function makeXMLHttpRequest(url, data, callback) {
                var request = new XMLHttpRequest();
                request.onreadystatechange = function() {
                    if (request.readyState == 4 && request.status == 200) {
                        if (request.responseText === 'success') {
                            callback('upload-ended');
                            return;
                        }
                        alert(request.responseText);
                        return;
                    }
                };
                request.upload.onloadstart = function() {
                    callback('PHP upload started...');
                };
                request.upload.onprogress = function(event) {
                    callback('PHP upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
                };
                request.upload.onload = function() {
                    callback('progress-about-to-end');
                };
                request.upload.onload = function() {
                    callback('PHP upload ended. Getting file URL.');
                };
                request.upload.onerror = function(error) {
                    callback('PHP upload failed.');
                };
                request.upload.onabort = function(error) {
                    callback('PHP upload aborted.');
                };
                request.open('POST', url);
                request.send(data);
            }
            // this function is used to generate random file name
            function getFileName(fileExtension) {
                var d = new Date();
                var year = d.getUTCFullYear();
                var month = d.getUTCMonth();
                var date = d.getUTCDate();
                return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
            }
            function getRandomString() {
                if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                    var a = window.crypto.getRandomValues(new Uint32Array(3)),
                        token = '';
                    for (var i = 0, l = a.length; i < l; i++) {
                        token += a[i].toString(36);
                    }
                    return token;
                } else {
                    return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
                }
            }
        </script>
        **<button id="myButton">Start Recording</button>**

    </body>
</html>

What you’re essentially asking is hot to carry out an action on button click.

For that you’ll need a button:

<button id="myButton">Click me!</button>

You’ll need a reference to the button:

var myButton = document.getElementById("myButton");

You’ll need a function to execute when the button is clicked:

function handleButtonClick(){
  console.log("Hello!");
}

And you’ll need to attach the function to the button using an event listener:

myButton.addEventListener("click", handleButtonClick, false);

And here’s how you put it together. Order of scripts and DOM elements is important.

<!DOCTYPE HTML>
<html lang="en">
  <head>
    <meta chraset="utf-8">
    <title>Event listener</title>
  </head>
  <body>
    <button id="myButton">Click me!</button>

    <script>
      function handleButtonClick(){
        console.log("Hello!");
      }

      var myButton = document.getElementById("myButton");
      myButton.addEventListener("click", handleButtonClick, false);
    </script>
  </body>
</html>

This might seem like a contrived example, but follow the principles here and you’ll be on your way to getting your page to do what you want.

1 Like

Thank you

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.