Друзья, я подписан RecordRTC захватить аудио на моем сайте, и успешно удалось загрузить записанный файл на сервер PHP через XMLHTTPRequest. Я загружаю сюда мой код:
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>
Следующие сценарии, используемые в файле представления, принимают микрофонный ввод и создают большой двоичный объект:
@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));
}
Других решений пока нет …