Record Audio Using the Users Microphone with HTML5

16,243

Solution 1

I have recently implemented a similar task you are trying to achieve using similar resources. You havent indicated that you need the audio uploaded as an mp3, so I am going to just show you how to upload a wav using recorderjs, using the source found here: https://github.com/cwilso/AudioRecorder

First things to note, recorderjs stores the uncompressed wav in a var called blob. This happens on line 101 of recorder js, more specifically in this function:

worker.onmessage = function(e){
  var blob = e.data;
  currCallback(blob);
}

The problem is that blob is locally declared in that function. We need to use it again, so for the sake of this example lets make it really easy to reach and make it global. So declare a variable blob outside of recorder js like so:

var blob = null;

Then modify the above function in recorderjs to store the data inside the globally declared 'blob' variable, the function should look like so:

worker.onmessage = function(e){
  blob = e.data;
  currCallback(blob);
}

Now we can use 'blob'. Now declare the following function somewhere,

function uploadAudio(){
        var fd = new FormData();
        var wavName = encodeURIComponent('audio_recording_' + new Date().getTime() + '.wav');
        console.log("wavName = " + wavName);
        fd.append('fname', wavName);
        fd.append('data', blob);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            //console.log(data);
            log.innerHTML += "\n" + data;
        });
}

Your server side code should use this:

<?php
if(!is_dir("recordings")){
    $res = mkdir("recordings",0777); 
}
move_uploaded_file($_FILES["file"]["tmp_name"],
  $res . $_FILES["file"]["fname"]);
?>

Note: $_FILES["file"]["tmp_name"] is what it sounds like. A temporary location of the file. This is done for you with the ajax call and form data.

Good luck, let me know if you run into problems.

Solution 2

As far as I can see, AudioRecorder exports as Blob. Blobs are something you can easily upload with XMLHttpRequest (and XMLHttpRequest uploads are something you can easily figure out with Google). In short, you don’t need FileReader (and may even skip FormData, since you’re only uploading a single Blob).

Keep in mind that people tend to not answer questions indicating no prior analysis by the OP; in this case you should have explained at least a) what kind of data you have to upload, and b) what exactly doesn’t work in you existing implementation. Here, you’re effectively asking people to cross two libraries (most of us never used either one, not to mention both). The truth is I might be wrong about Blobs, but you actually know that better than me and just failed to inform. (Don’t get me wrong, though; I hope I’m right, and you’re gonna get your code working soon.)

Share:
16,243
three3
Author by

three3

Updated on June 11, 2022

Comments

  • three3
    three3 about 2 years

    I am very close to having a little project of mine done, however, I have run into a slight problem I cannot seem to figure out on my own. What I ultimately want to do is record a user's voice from the users microphone, and then upload the recording to my server when they are done. I am using the code from this project: https://github.com/cwilso/AudioRecorder

    It works great, but I am needing to add a feature that it does not include out of the box. I need to be able to upload the file to my server after the recording has finished. With the default code, the file can be downloaded locally to my computer, but not uploaded. So I did some research and I came across another similar project that has the uploading feature. However, the rest of the project is more buggy in my opinion. So I tried adding the "uploading code" from the following project: https://github.com/nusofthq/Recordmp3js

    Javascript code:

    function uploadAudio(mp3Data){
        var reader = new FileReader();
        reader.onload = function(event){
            var fd = new FormData();
            var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
            console.log("mp3name = " + mp3Name);
            fd.append('fname', mp3Name);
            fd.append('data', event.target.result);
            $.ajax({
                type: 'POST',
                url: 'upload.php',
                data: fd,
                processData: false,
                contentType: false
            }).done(function(data) {
                //console.log(data);
                log.innerHTML += "\n" + data;
            });
        };      
        reader.readAsDataURL(mp3Data);
    }
    

    PHP code:

    <?php
    if(!is_dir("recordings")){
        $res = mkdir("recordings",0777); 
    }
    
    // pull the raw binary data from the POST array
    $data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
    $filename = urldecode($_POST['fname']);
    
    // write the data out to the file
    $fp = fopen('recordings/'.$filename, 'wb');
    fwrite($fp, $decodedData);
    fclose($fp);
    ?>
    

    I have tried combining this code to the project located at https://github.com/cwilso/AudioRecorder, but to no avail. What do I need to change in the Javascript code above and where do I need to place it? Any help is greatly appreciated!

    PS: I know this only works in Chrome, FireFox, and Opera.

  • three3
    three3 almost 10 years
    Thanks for your answer and input. What I really need to know then is where (what file) would I add the XMLHttpRequest to upload the blob in the AudioRecorder project?
  • K Lee
    K Lee almost 10 years
    My guess would be there is no file at all (Blob is not a file). As I never used AudioRecorder, I can only tell you I see exportWAV method in the source (which appears to be exporting Blob, but you should try it before believing my word). If it does, that Blob is exactly what you want to pass into your XHR to upload.
  • three3
    three3 almost 10 years
    The exportWAV method you mentioned, I see it mentioned in several of the AudioRecorder files. Which file would are you referring to when you speak of the exportWAV method? After I know this, I will give the XMLHttpRequest a shot. Thanks again!
  • K Lee
    K Lee almost 10 years
    You do realise I don’t know every API on the planet, right? What you’re asking is no longer about JavaScript, it’s about that specific library you’re using. I assume you already know how to export from AudioRecorder, otherwise how can you be sure you original code doesn’t work in the first place?