1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Combined portion of another script created no success for upload

Discussion in 'JavaScript' started by chrisj, Oct 6, 2017.

  1. #1
    The script RecordRTC allows for recording web cam via web page.
    One of their scripts is just for manual recording, one is for auto recording and uploading.
    Both scripts work successfully individually.
    This code works successfully for manual start/stop recording:

    <!DOCTYPE html>
    <html>
        <head>
    </head>
    
    <body>
    <style>
        html, body {
            margin: 0!important;
            padding: 0!important;
            overflow: hidden!important;
            width: 100%;
        }
    </style>
    
    <title>Video Recording | RecordRTC</title>
    <h1>Simple Video Recording using RecordRTC</h1>
    
    <br>
    
    <button id="btn-start-recording">Start Recording</button>
    <button id="btn-stop-recording" disabled>Stop Recording</button>
    
    <hr>
    <video controls autoplay></video>
    
    <script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
    <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
    <script>
    var video = document.querySelector('video');
    function captureCamera(callback) {
        navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function(camera) {
            callback(camera);
        }).catch(function(error) {
            alert('Unable to capture your camera. Please check console logs.');
            console.error(error);
        });
    }
    function stopRecordingCallback() {
        video.src = video.srcObject = null;
        video.src = URL.createObjectURL(recorder.getBlob());
        video.play();
        recorder.camera.stop();
        recorder.destroy();
        recorder = null;
    }
    var recorder; // globally accessible
    document.getElementById('btn-start-recording').onclick = function() {
        this.disabled = true;
        captureCamera(function(camera) {
            setSrcObject(camera, video);
            video.play();
            recorder = RecordRTC(camera, {
                type: 'video'
            });
            recorder.startRecording();
            // release camera on stopRecording
            recorder.camera = camera;
            document.getElementById('btn-stop-recording').disabled = false;
        });
    };
    document.getElementById('btn-stop-recording').onclick = function() {
        this.disabled = true;
        recorder.stopRecording(stopRecordingCallback);
    };
    </script>
        </body>
    </html>
    Code (JavaScript):

    I compared the two scripts and copied and pasted the 'upload' portion of their other auto-record script, into the above script, in hopes of manual start/stop and then upload.
    So, no surprise it doesn't even record now, but here is the combined code. I'm hoping maybe someone can glance over it and make a suggestion as to how to accomplish my goal of start, stop and then upload. Much thanks for any help.

    <!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>
    </head>
    
    <body>
    <style>
        html, body {
            margin: 0!important;
            padding: 0!important;
            overflow: hidden!important;
            width: 100%;
        }
    </style>
    
    <title>Video Recording | RecordRTC</title>
    <h1>Simple Video Recording using RecordRTC</h1>
    
    <br>
    
    <button id="btn-start-recording">Start Recording</button>
    <button id="btn-stop-recording" disabled>Stop Recording</button>
    
    <hr>
    <video controls autoplay></video>
    
    <script>
    var video = document.querySelector('video');
    function captureCamera(callback) {
        navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function(camera) {
            callback(camera);
        }).catch(function(error) {
            alert('Unable to capture your camera. Please check console logs.');
            console.error(error);
        });
    }
    function stopRecordingCallback() {
        video.src = video.srcObject = null;
        video.src = URL.createObjectURL(recorder.getBlob());
        video.play();
        recorder.camera.stop();
        recorder.destroy();
        recorder = null;
    }
    var recorder; // globally accessible
    document.getElementById('btn-start-recording').onclick = function() {
        this.disabled = true;
        captureCamera(function(camera) {
            setSrcObject(camera, video);
            video.play();
            recorder = RecordRTC(camera, {
                type: 'video'
            });
            recorder.startRecording();
            // release camera on stopRecording
            recorder.camera = camera;
            document.getElementById('btn-stop-recording').disabled = false;
        });
    };
    document.getElementById('btn-stop-recording').onclick = function() {
        this.disabled = true;
        recorder.stopRecording(stopRecordingCallback);
    };
    
    [B]// 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('Upload started...');
                    };
                    request.upload.onprogress = function(event) {
                        callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
                    };
                    request.upload.onload = function() {
                        callback('progress-ending');
                    };
                    request.upload.onload = function() {
                        callback('Upload Complete.');
                    };
                    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, '');
                    }
                };[/B]
    </script>
        </body>
    </html> 
    Code (JavaScript):

     
    chrisj, Oct 6, 2017 IP
  2. lektrikpuke

    lektrikpuke Well-Known Member

    Messages:
    297
    Likes Received:
    1
    Best Answers:
    1
    Trophy Points:
    113
    #2
    Do you have an element with an id of 'your-video-id'? That might be part/most of the problem. Also there's a bracket
    [B]
    Code (markup):
    , was that from copying and pasting here? Why mixing and matching between js and jQuery? Sure, it'll work, but ... Also, I would go with $.post instead of
    makeXMLHttpRequest. I realize you're copying and pasting, but life would be easier, and code would read nicer.
     
    lektrikpuke, Dec 9, 2017 IP