Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload captured audio to server. JS Jquery PHP

I am using this

<button onclick="startRecording(this);">record</button>
  <button onclick="stopRecording(this);" disabled>stop</button>

  <h2>Recordings</h2>
  <ul id="recordingslist"></ul>

  <h2>Log</h2>
  <pre id="log"></pre>

  <script>
  function __log(e, data) {
    log.innerHTML += "\n" + e + " " + (data || '');
  }

  var audio_context;
  var recorder;

  function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
    __log('Media stream created.' );
    __log("input sample rate " +input.context.sampleRate);

    // Feedback!
    //input.connect(audio_context.destination);
    __log('Input connected to audio context destination.');

    recorder = new Recorder(input, {
                  numChannels: 1
                });
    __log('Recorder initialised.');
  }

  function startRecording(button) {
    recorder && recorder.record();
    button.disabled = true;
    button.nextElementSibling.disabled = false;
    __log('Recording...');
  }

  function stopRecording(button) {
    recorder && recorder.stop();
    button.disabled = true;
    button.previousElementSibling.disabled = false;
    __log('Stopped recording.');

    // create WAV download link using audio data blob
    createDownloadLink();

    recorder.clear();
  }

  function createDownloadLink() {
    recorder && recorder.exportWAV(function(blob) {
      /*var url = URL.createObjectURL(blob);
      var li = document.createElement('li');
      var au = document.createElement('audio');
      var hf = document.createElement('a');

      au.controls = true;
      au.src = url;
      hf.href = url;
      hf.download = new Date().toISOString() + '.wav';
      hf.innerHTML = hf.download;
      li.appendChild(au);
      li.appendChild(hf);
      recordingslist.appendChild(li);*/
    });
  }

  window.onload = function init() {
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      navigator.getUserMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);
      window.URL = window.URL || window.webkitURL;

      audio_context = new AudioContext;
      __log('Audio context set up.');
      __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
    } catch (e) {
      alert('No web audio support in this browser!');
    }

    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      __log('No live audio input: ' + e);
    });
  };
  </script>

   <script src="js/jquery-1.11.0.min.js"></script>
  <script src="recordmp3.js"></script>

To capture audio and offer an mp3 download but what I really need to do is upload the recordings to the server and as a bonus if I could rename the files before upload that would make it perfect! Can't show an example of what I've tried as I have no idea where to start on this one, any help greatly appreciated.

The flow would be to capture a handful of short recordings, rename them then hit an upload button which will upload them as mp3's then redirect to a success page.

Full code here https://github.com/Audior/Recordmp3js

like image 468
Glen Keybit Avatar asked Apr 18 '21 06:04

Glen Keybit


1 Answers

You should upload the data as a XMLHttpRequest, however on the server side you should save it to a file with a custom name. This is also safer, since you can very easily avoid file traversal attacks by not specifying a path (From what I've understood, other people can't upload files to your computer/server, however I still believe you should approach this method because it is a great introduction to protecting an application with basic security measures).

You can use the following (modified) answer, taken from here, to do the job. This is how the JS function createDownloadLink should look after the modifications:

function createDownloadLink() {
  recorder && recorder.exportWAV(function(blob) {
    // Generate the 'File'
    var data = new FormData();
    data.append('file', blob);

    // Make the HTTP request
    var oReq = new XMLHttpRequest();

    // POST the data to upload.php
    oReq.open("POST", 'upload.php', true);
    oReq.onload = function(oEvent) {
      // Data has been uploaded
    };
    oReq.send(data);
  });
}

On the PHP side, however, you should also make some modifications, since this is now a classic file upload, rather than a POST request with the data being sent as a parameter. Modify upload.php like so (information about moving uploaded files taken from here):

<?php
// Make sure recordings folder exists
if(!is_dir("recordings")){
    $res = mkdir("recordings",0777); 
}

// Declare file name
$filename = 'recordings/' . 'audio_recording_' . date( 'Y-m-d-H-i-s' ) .'.mp3';

// Move the uploaded file to the directory
move_uploaded_file($_FILES['file']['tmp_name'], $filename));
?>
like image 146
Xiddoc Avatar answered Oct 24 '22 03:10

Xiddoc