Reputation: 223
I am building a Django WebApp that records multiple speakers, manipulates the files and pushes the result to an IBM Speech Processing tool. I've been stuck at the recording part for two days and would appreciate some help.
My goal is to be able to store .wav files in my database, that I can manipulate and send to the IBM tool.
In JS, this is how I found how to record the audio.
function handlerFunction(stream) {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive"){
let blob = new Blob(audioChunks,{type:'audio/wav'});
recordedAudio.src = URL.createObjectURL(blob);
recordedAudio.controls=true;
recordedAudio.autoplay=true;
sendData(blob)
}
}
}
function sendData(data) {
$('.passAudio').val(data);
}
I can replay it in the audio tag and I'm attempting to pass it as a hidden input. So far, it's telling me it passes an Blob object, but I don't know what to do with that.
<audio id=recordedAudio></audio>
<input type="hidden" accept="audio/*" id="0" name="audio" class="passAudio">
I'm trying to get it to somehow store in my default storage, but I have no idea if this is even in the correct direction. I'm also unsure how to check if it's been correctly saved.
# views.py
if request.method == 'POST':
blob = request.POST.getlist('audio')
path = default_storage.save('audio/'+'123'+'.wav', ContentFile(blob.read()))
default_storage.size(path)
default_storage.open(path).read()
I'm sure a lot of this is wrong, as I don't understand how to pass a file (or a blob) from JS to python and store it.
My questions are
How do I transform the blob into a file that I can then pass to python?
How do I check it's been stored correctly?
Upvotes: 2
Views: 2106
Reputation: 66
From javascript function, you can use ajax to send audio blob to the server.
function sendData(data)
{
let csrftoken = getCookie('csrftoken');
let response=fetch("/voice_request", {
method: "post",
body: data,
headers: { "X-CSRFToken": csrftoken },
})
}
server-side:
def voice_request(request):
print(request.body)
f = open('./file.wav', 'wb')
f.write(request.body)
f.close()
return HttpResponse('audio received')
to get cscrf token:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
ref: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
Upvotes: 4