【问题标题】:Uploading Sound Blob on Server Using Laravel使用 Laravel 在服务器上上传声音 Blob
【发布时间】:2018-03-06 11:43:29
【问题描述】:

朋友们,我正在关注RecordRTC 在我的网站上捕获音频,并成功地通过 XMLHTTPRequest 将录制的文件上传到 PHP 服务器上。我在这里上传我的代码:

 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>
这是我的 Save.php 文件:

<?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';
?>

现在我必须在我的 Laravel 项目中应用这种机制,我是 Laravel 框架的新手,不知道如何实现它。请帮助我找到解决方案。 问候

【问题讨论】:

  • 您是否阅读了有关上传文件以及如何存储它们的文档?
  • 是的,我读到了。问题在这里我正在处理我使用 getusermedia() 捕获的 blob...问题是在目录中上传。

标签: javascript php laravel laravel-5.3 recordrtc


【解决方案1】:

视图文件中使用的以下脚本接受 mic 输入并创建 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

因此,您将能够在控制器中使用以下代码存储实际的 wav 文件:

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));
}

【讨论】:

  • 你有没有自己实现过这个机制?如果是,请与我分享一些演示!
  • 我已经在我目前正在进行的项目中实现了它,但不幸的是我还没有提供现场演示。如果您需要有关代码的任何其他信息,请告诉我。
  • 是的,如果您向我展示您使用该代码的那个文件,将非常高兴,谢谢
  • 是的,如果您向我展示您使用该代码的那个文件,将非常高兴,谢谢
  • 请在我的回答中找到我使用的代码的更详细版本...
猜你喜欢
  • 1970-01-01
  • 2018-10-28
  • 2020-12-13
  • 2010-11-07
  • 2021-10-10
  • 2020-11-13
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
相关资源
最近更新 更多