How to upload video recorded with MediaRecorder API using PHP?

892 views Asked by At

I am working on a video recording task using MediaRecorder API. As from frontend I can start the webcam, record video, play the recorded video and download the video. enter image description here

But when I try to upload the video to php server, it's not at all working. I don't really understand why it is happening, I also tried using so many methods but none of it is working. Please check the code attatched below.

JS:-

let mediaRecorder
let recordedBlobs

const errorMsgElement = document.querySelector('span#errorMsg');
const recordedVideo = document.querySelector('video#recorded');
const recordButton = document.querySelector('button#record');
const playButton = document.querySelector('button#play');
const downloadButton = document.querySelector('button#download');

document.querySelector("button#start").addEventListener("click", async function() {
    const hasEchoCancellation = document.querySelector("#echoCancellation").checked

    const constraints = {
        audio: {
            echoCancellation:{
                exact: hasEchoCancellation
            }
        },
        video: {
            width: 1280,
            height: 720
        }
    }

    await init(constraints)
})

async function init(constraints) {
    try {
        const stream  = await navigator.mediaDevices.getUserMedia(constraints)
        handleSuccess(stream)
    } catch(e) {
        console.log(e)
    }
}

function handleSuccess(stream) {
    recordButton.disabled = false

    window.stream = stream

    const gumVideo = document.querySelector("video#gum")

    gumVideo.srcObject = stream
}

recordButton.addEventListener("click", () => {
    if(recordButton.textContent === "Record") {
        startRecording()
    } else {
        stopRecording()
        recordButton.textContent = 'Record'
        playButton.disabled = false
        downloadButton.disabled = false
    }
})

function startRecording() {
    recordedBlobs = []

    let options = {
        mimeType: "video/webm;codecs=vp9,opus"
    }

    try {
        mediaRecorder = new MediaRecorder(window.stream, options)
    } catch(e) {
        console.log(e)
    }

    recordButton.textContent = "Stop Recording"
    playButton.disabled = true
    downloadButton.disabled = true

    mediaRecorder.onstop = (event) => {
        console.log('Recording Stopped')
    }
    mediaRecorder.ondataavailable = handleDataAvailable
    mediaRecorder.start()
}

function handleDataAvailable(event) {
    if(event.data && event.data.size > 0) {
        recordedBlobs.push(event.data)
    }
}

function stopRecording() {
    mediaRecorder.stop()
}

playButton.addEventListener('click', function() {
    const superBuffer = new Blob(recordedBlobs, {
        type: 'video/webm'
    })
    var file = new File([superBuffer], 'test.webm')
    var url = window.URL.createObjectURL(superBuffer)
    // var video = blobToFile(superBuffer, 'test.webm')
    sendToServer(file)
    recordedVideo.src = null
    recordedVideo.srcObject = null
    recordedVideo.src = url
    recordedVideo.controls = true
    recordedVideo.play()
})

downloadButton.addEventListener('click', () => {
    const blob = new Blob(recordedBlobs, {type: 'video/mp4'});
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'test.mp4';
    document.body.appendChild(a);
    a.click();
    setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }, 100);
});

function sendToServer(file) {
    let url = 'send.php'
    let headers = {
        'Content-Type': 'multipart/form-data'
    }
    var formData = new FormData()
    formData.append("file", file)
    axios.post(url, formData, headers)
        .then((response) => {
            console.log(response.data)
        })
        .catch((error) => {
            console.log(error.response)
        })
}

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

PHP:-

$target_dir = "uploads/";
$target_file = $target_dir . 'test.webm';
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    echo "File uploaded successfully";
} else {
    echo "File not uploaded";
}
print_r($_FILES['file']['error']);

No matter how much I tried, I can't figure out why it is not working. It is showing that "File not uploaded" like it can't read the file from tmp_name. Please help me fix the problem. Any help on this problem will be really appreciated. Thank you.

0

There are 0 answers