Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Recorded Audio File to Web Server With PHP

I'm using Recorder.js which allows users to create their own sound recording from their microphone input. I'm new to this so I'm using this site as a point of reference.

This code creates a downloadable .wav file:

<html>
    <head>
        <script src="js/recorderjs/recorder.js"></script>
        <script src="js/main.js"></script>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    </head>

    <body>
        <img id="record" src="mic.png" onclick="toggleRecording(this);"><br>

        <img src="save.svg" onclick="saveAudio();">

        <form action="savefile.php" method="post">
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

This starts and stops the recording:

<img id="record" src="mic.png" onclick="toggleRecording(this);">

And this downloads the .wav file from the recorder.js script:

<img src="save.svg" onclick="saveAudio();">

I'm using this PHP script to try and save the .wav file to the /audio directory:

<?php

$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
    if(! mkdir($save_folder)) {
        die("failed to create save folder $save_folder");
    }
}

$key = 'filename';
$tmp_name = $_FILES["audiofile"]["tmp_name"];
$upload_name = $_FILES["audiofile"]["name"];
$type = $_FILES["audiofile"]["type"];
$filename = "$save_folder/$upload_name";
$saved = 0;
if(($type == 'audio/x-wav' || $type == 'application/octet-stream') && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) ) {

    $saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}

?>

Now, what I'm hoping for is someone to help me with a PHP script which uploads the .wav files to the folder /audio instead of having the user download the file.

Any help with this would be greatly appreciated.

like image 680
Enijar Avatar asked May 29 '13 14:05

Enijar


1 Answers

I think you can't use usuall http file fields, because they expect a local path. You could try a upload with AJAX.

var req = null;
var url = "savefile.php";
var data = "":   // you have to check how to get the data from your saveAudio() method

(window.XMLHttpRequest) ? req = new XMLHttpRequest() : (window.ActiveXObject) ? req = new ActiveXObject("Microsoft.XMLHTTP") : req = false; 
req.open(method, url, true);
req.setRequestHeader("Content-Type", "multipart/form-data");

if(data != null && data != "")
{
  req.setRequestHeader("Content-length", data.length);
  req.send(data);
}

You yust need to find out how you can get the filecontent from your saveAudio() function and fill it into the data variable.

And maybe this can help you too uploading files with ajax

like image 118
Radon8472 Avatar answered Nov 10 '22 11:11

Radon8472