2

Friends, Im following RecordRTC to capture audio on my website, and successfully managed to upload Recorded file on PHP server via XMLHTTPRequest. Im uploading here my Code:

 var audio_context;
  var recorder;
  var isMouseDown = false;
  var fileType = 'audio';
  var fileName = 'ABCDEF.wav';

  function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
    __log('Media stream created.');
	console.log('Media stream created.');

    // Uncomment if you want the audio to feedback directly
    //input.connect(audio_context.destination);
    //__log('Input connected to audio context destination.');

    recorder = new Recorder(input);
    __log('Recorder initialised.');
	console.log('Recorder Initialized');
  }

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

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

    // create WAV download slink using audio data blob
    createDownloadLink();
    recorder.clear();    

  }


  function createDownloadLink()
  {
    recorder && recorder.exportWAV(function(blob)
	{
		var counter = 0;
		
		var url = URL.createObjectURL(blob);
      
		var fileName = 'Recording'+counter+'.wav';
		
		var fileObject = new File([blob], fileName, {
                            type: 'audio/wav'
                        });
						
		var formData = new FormData();

                        // recorded data
		formData.append('audio-blob', fileObject);

                        // file name
        formData.append('audio-filename', fileObject.name);
		
		
		$.ajax({
                            url: 'save.php', // replace with your own server URL
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            type: 'POST',
                            success: function(response) {
                                if (response === 'success') {
                                    alert('successfully uploaded recorded blob');
									console.log('Successfully Uploaded Recorded Blob');
                                    // file path on server
                                    var fileDownloadURL = '/uploads/' + fileObject.name;

                                
								} else 
								{
                                    alert(response); // error/failure
                                }
                            }
                        });

    });

  }


  window.onload = function init() {
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
      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);
    });
  };
 <button onclick="startRecording(this);">record</button>
  <button onclick="stopRecording(this);" disabled>stop</button>
and this is my Save.php file:

<?php
// upload directory
$filePath = 'uploads/' . $_POST['audio-filename'];

// path to ~/tmp directory
$tempName = $_FILES['audio-blob']['tmp_name'];

// move file from ~/tmp to "uploads" directory
if (!move_uploaded_file($tempName, $filePath)) {
    // failure report
    echo 'Problem saving file: '.$tempName;
    die();
}

// success report
echo 'success';
?>

Now i have to apply this mechanism in my Laravel project,Im new on Laravel Framework and have no clue how can i make it happen. Kindly help me to find a solution. Regards

3
  • Have you read the documentation on uploaded files and how to store them? Commented Sep 25, 2017 at 13:41
  • laravel.com/docs/5.5/filesystem#file-uploads Commented Sep 25, 2017 at 13:54
  • yes, i read that. problem is here im dealing with a blob that i captured using getusermedia()... problem is to upload in a directory. Commented Sep 25, 2017 at 15:53

1 Answer 1

2

The following scripts used in the view file take mic input and create the blob:

@section('scripts')
<script src="https://cdn.webrtc-experiment.com/RecordRTC.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

<script>
function captureMicrophone(callback) {
    navigator.mediaDevices.getUserMedia({audio: true}).then(callback).catch(function(error) {
        alert('Unable to access your microphone.');
        console.error(error);
    });
}

var recorder;

//on click of a button representing microphone
$('#inputFields').on('click','*[class*=microphoneBtn]',function(){
    var audio = $('$audio'); //this refers to an HTML audio element
    var button = this;

    if(recorder == null || recorder.state === 'stopped'){ //start recording
        captureMicrophone(function(microphone) {
            setSrcObject(microphone, audio);
            audio.muted = true;
            audio.play();

            recorder = RecordRTC(microphone, {
                type: 'audio',
                recorderType: StereoAudioRecorder,
                desiredSampRate: 16000
            });
        recorder.startRecording();
        recorder.microphone = microphone;
    }else{ //stop recording
        recorder.stopRecording(function(){
            var blob = this.getBlob();  //get actual blob file
            audio.src = URL.createObjectURL(blob); //set src of audio element    
            audio.muted = false;
            audio.play();
            recorder.microphone.stop();
        });
    }    

});
</script>


//on click of the save button, save the audio file to server
$('#inputFields').on('click','*[class*=saveBtn]',function(){
    var blob = recorder.getBlob();
    var formdata = new FormData();
    formdata.append('audio-blob', blob);

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        type: 'POST',
        url: //your url,
        data: formdata,
        processData: false,
        contentType: false,
        success: function (data) {
            //success message           
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            //error message 
        }                              
    });

});
@endsection

Thus, you will be able to store the actual wav file using the following code in your Controller:

public function store(Request $request) {
    $blobInput = $request->file('audio-blob');

    //save the wav file to 'storage/app/audio' path with fileanme test.wav
    Storage::put('audio/test.wav', file_get_contents($blobInput));
}
Sign up to request clarification or add additional context in comments.

5 Comments

have u ever implemented this mechanism by urself ? if yes then please share some demo with me !
I've implemented it in a project I'm currently working on, but unfortunately I don't have a live demo to offer yet. If you require any additional info on the code, do let me know.
yes it would be a great pleasure if u show me that file in which u used that code, thanks
yes it would be a great pleasure if u show me that file in which u used that code, thanks
please, find in my answer a more detailed version of the code I used...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.