Do not upload media after recording with getUserMedia

I am facing an issue with getUserMedia where I am unable to upload the video after recording. When I click the "Stop And Upload" button, I receive a null response. Can anyone provide assistance in resolving this? Thank you.

Upon clicking the "Stop And Upload" button, I encounter a null response and need the file to be directly uploaded to the webserver.

<div class="content">

<video playsinline poster="./poster.png" onclick="this.play();"></video>
<button id="btn-stop-recording" type="button" disabled>Stop And Upload</button>

<script src="./RecordRTC.js"></script>
//library URL (https://): webrtc-experiment.com/RecordRTC.js
<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.muted = false;
    video.volume = 1;
    //video.src = URL.createObjectURL(recorder.getBlob());
    video.src = window.URL.createObjectURL(recorder.getBlob());
    document.write(video.src);
    var fd = new FormData();
    fd.append('fname', 'test.webm');
    fd.append('data', video.srcObject);
    $.ajax({
        type: 'POST',
        url: './true.php',
        data: fd,
        processData: false,
        contentType: false
    }).done(function(data) {
           console.log(data);
    });
}

var recorder; // globally accessible

document.getElementById('btn-start-recording').onclick = function() {
    this.disabled = true;
    captureCamera(function(camera) {
        video.muted = true;
        video.volume = 0;
        video.srcObject = camera;

        recorder = RecordRTC(camera, {
            type: 'video',
            mimeType: 'video/webm'
        });

        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>
<div>

File true.php >>>>

<?php
foreach(array('video') as $type) {
    if (isset($_FILES["${type}-blob"])) {

        echo 'uploads/';

        $fileName = $_POST["${type}-filename"];
        $uploadDirectory = 'uploads/'.$fileName;

        if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
            echo(" problem moving uploaded file");
        }

        echo($fileName);
    }
}
?>

After checking the console log, it appears that the file is being sent to the server. However, upon receiving the file in the PHP script, it fails to upload to the server.

POST DATA FROM AJAX CALL:

POST /true.php HTTP/1.1
Host: localhost:9090
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0
Accept: */*
Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Content-Type: multipart/form-data; boundary=---------------------------39520532461108107029652486848
Content-Length: 644254
Origin: http://localhost:9090
Connection: close
Referer: http://localhost:9090/

-----------------------------39520532461108107029652486848
Content-Disposition: form-data; name="fname"

test.webm
-----------------------------39520532461108107029652486848
Content-Disposition: form-data; name="data"; filename="blob"
Content-Type: video/webm

Answer №1

This subject can be quite perplexing, and with all due respect, there might be some confusion on your part. It's actually not getUserMedia that is responsible for the recording process; instead, it's RecordRTC. The data you aim to upload is the content of the Blob obtained from recorder.getBlob(). Keep in mind that this Blob contains binary data, which may not make much sense unless processed using a tool like ebml.

Additionally, note that .getBlob() returns a Promise, requiring the use of .then() to determine when the Blob is ready.

You are almost there. Your goal is to upload the Blob. With a few adjustments, you will be set to proceed.

function stopRecordingCallback() {
    recorder.getBlob()
    /* getBlob process completed successfully */
    .then (function(blob) {
        const fd = new FormData()
        fd.append('fname', 'test.webm')
        fd.append('data', blob)
        $.ajax({
            type: 'POST',
            url: './true.php',
            data: fd,
            processData: false,
            contentType: false
        })
        .done(function(data) {
           console.log(data)
    })
    /* getBlob's promise rejected */
    .catch(console.err)
}

I have not tested this code myself, but it aligns closely with my previous experiences.

It appears that you may be attempting to configure your <video> element to display the recorded video. If so, I recommend focusing on getting the upload functionality working first before proceeding with the preview feature.

Pro tip: Simplify your WebRTC media code by incorporating async / await instead of relying solely on .then() and callbacks. Becoming proficient in utilizing async / await can greatly improve the readability and conciseness of your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to retrieve the session value using JavaScript in a C# application

Currently, I am attempting to retrieve four values from the session. However, I am only able to fetch two of them, while the other two seem to be missing. As a beginner, I apologize if my question comes across as too simplistic. Within a tree view, I have ...

MinifyJS - optimize all .js files within a directory

Seeking assistance to finalize my build process: I am currently transpiling es6 > es5 using babel. Once that is complete, I aim to minify all my .js files recursively with uglifyJS solely using NPM scripts (no grunt or gulp). My Requirements; Convert ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

A guide on using jQuery to iterate through 3 separate div elements

Seeking assistance with creating a dynamic loop for multiple divs (3 or more) using jQuery. The desired outcome is to have the main image div on the homepage rotate with other divs, changing both the background image and links within each div. I initially ...

Authenticating Users with Laravel and Vue.js

In my Vue.js application, I have implemented a login system. The main script in my main.js file includes the necessary imports and configurations: import Vue from 'vue'; import NProgress from 'nprogress'; import Resource from 'vue ...

Nodejs - how to achieve interoperability between mjs and js files through importing and requiring?

I'm fairly new to JavaScript and Node.js. Based on my research, it seems that ES6 import is not compatible with Node.js, so I've resorted to using experiment mode by renaming my file to .mjs. This workaround generally works, except when the .mjs ...

Is there a way to activate an event listener specifically for clicking on an image?

Presently, my code consists of a div element that holds two images. The first image has a z-index of 1 and appears behind the second image. I am looking to implement an event listener that will be triggered only when the first image is clicked. Interestin ...

The $watch function is triggered even when the expression remains unchanged

Within my controller, I have a variable named datetime that gets updated by a timer every second. What I need to accomplish is some work when the day changes. To achieve this, I set up the following watcher: $scope.$watch("datetime | date: 'MM/dd/yyy ...

React throws an error when attempting to switch to a login element with an invalid return type

I'm encountering difficulties connecting my login and signup pages to the home page in React. Here is the project's basic structure: --src --assets --components --elements --layout --login_components Login.js --signup_c ...

Is there a way to swap out multiple characters within a string when using ng-repeat in AngularJS?

How can I replace multiple characters in a string using ng-repeat in AngularJS? I've tried the following code, but it's not working. I need to remove #, _, and . from the strings in my list. How can I achieve this in AngularJS? <body> &l ...

Tips for improving the readability of my code

This code snippet pertains to handling a POST request in Express.js with MongoDB integration. router.post('/', function(req, res){ var data = req.body; Tag.find({name: data.name}).limit(1).exec( function(err, result){ if(err) { // ...

Discover a JavaScript table using a for loop

Currently, I'm in the process of setting up a search bar within a table that has been populated by looping data retrieved from an API. My goal is to allow users to search for specific entries either by name or email. Unfortunately, I seem to be encoun ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Error encountered in App.js on line 29: Unable to access the property 'map' as it is undefined

Currently enrolled in the University of Helsinki Full Stack Open course, I am facing a challenging error while working on my React web app. The app retrieves data from the Rest Countries API (https://github.com/apilayer/restcountries) and I am trying to di ...

Using default value in PHP and JavaScript for a select dropdown

I have an array of cities stored in associative arrays using PHP. I am utilizing JavaScript's "on change" event to capture the value of each item. In the future, I am considering implementing geolocation for setting a default item. Here are my arrays ...

Asynchronous database calls within a loop that do not wait

I'm facing a challenge while trying to access a database during JSON parsing. This particular piece of code has become a nightmare for me: function loopColumns(val, cb){ db.one('select tag_name from t_tag where tag_id = $1', val) ...

Angular NgClass Issue (Unable to bind to 'ngClass' as it is not recognized as a property of 'a')

Hi there! I am relatively new to using Angular and I am currently facing an issue while attempting to dynamically add a Bootstrap class to my HTML based on the active tab. Unfortunately, I am encountering an error. Can anyone provide assistance? The error ...

Animate a div to sense whether it has reached the top or bottom position

Is it possible for a div to animate when it reaches almost halfway while scrolling? I'm looking to achieve this effect on a sticky sidebar, similar to how it works on this website: sample This is the code I have: $(function(){ // document ready ...

Using async/await with Middleware in Express

I'm struggling to grasp the concept of writing middleware in Express that uses async/await without leaving a floating Promise after execution. Despite reading numerous blogs and StackOverflow posts, it appears that there is a common pattern for utiliz ...

Changing from system mode to dark mode or light mode

Within my Next.js web application, I am implementing MUI to facilitate the transition between system, light, and dark modes. Persistence between sessions is achieved by storing the selected theme in local storage. The user has the option to change the them ...