Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save MediaRecorder stream to OGG file in PHP? Including Metadata

I am providing audio recording to my users within the browser, using Javascript:

navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => 
{
    stream = _stream;
    recorder = new MediaRecorder(stream);

    recorder.ondataavailable = e => 
    {
        // push data to chunks
        chunks.push(e.data);

        // recording has been stopped
        if(recorder.state == 'inactive') 
        {
            blob = new Blob(chunks, {type: media.type });
            blob_url = URL.createObjectURL(blob);
            
            $('.rec_result_audio').attr({
                'src': blob_url
            });
            
            // send data to server
            // append file to object to be sent
            var filedata = new FormData();
            filedata.append('recfile', blob, blob_url);

            // send by AJAX/POST
        }
    };
}

In PHP I get and store the stream like this:

if(!empty($_FILES)) 
{
    $filename = $_FILES['recfile']['name'];
    $file_locationtmp = $_FILES['recfile']['tmp_name'];
    $filetype = $_FILES['recfile']['type'];
    $filesize_bytes = $_FILES['recfile']['size'];
    
    // add file extension to string
    $_FILES['recfile']['name'] = $_FILES['recfile']['name'].'.ogg';

    // save to filesystem
}

Now the OGG file (webm with opus codec) is stored on the server. However, all the metadata is missing. And thus the playbar does not work. See here for more info: HTML5 Audio - Progressbar/Playbar is not working for OGG audio file / Issue with 206 Partial Content

ogg metadata empty

Length is missing. Also the Bit rate, Channels and Audio sample rate.

Obviously the direct saving to the file system with PHP is not enough.

What is missing in the PHP code, so that the file is recognized as an OGG file later on?

Do I have to add metadata, and if so, how?

like image 633
Avatar Avatar asked Apr 11 '21 04:04

Avatar


1 Answers

I am probably missing something obvious, but - shouldn't you specify that you want the Javascript stream to be OGG/Vorbis?

recorder = new MediaRecorder(stream, { mimeType: "audio/ogg; codecs=vorbis" });

I might be mistaken, but the file you get:

Now the OGG file (webm with opus codec) is stored on the server. However, all the metadata is missing.

is not actually an OGG file -- it is a WEBM file. As such, giving it an .ogg extension instead of .webm, as you do, probably confuses the system, and that's why the file appears "unreadable and missing metadata".

like image 143
LSerni Avatar answered Oct 09 '22 17:10

LSerni