[英]How to convert a blob URL to a audio file and save it to the server
[英]How to upload large audio file to a django server given a blob url?
我有一個JavaScript,它使用MediaRecorder
記錄音頻並將二進制數據推送到數組chunk
。 用戶完成記錄后,數據將轉換為blob
並加載到HTML的audio
元素中進行播放。 我的問題是現在嘗試將這些數據同時加載到Django服務器上。 我見過的大多數示例上傳腳本都讓用戶手動將音頻文件加載到表單的input
元素中,並手動單擊提交按鈕,但是我的數據已經加載到Blob文件中,因此我不確定如何繼續。
HTML
<div id="buttons">
<form>
<button id="record_btn" style="">Record</button>
<input id="stop_btn" type="submit" value="Stop" disabled>
<audio id="audio" controls>
<source id="source" src="" type="audio/ogg"/>
</audio>
</form>
</div>
使用Javascript
var record = document.querySelector('#record_btn');
var stop = document.querySelector('#stop_btn');
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
console.log('getUserMedia supported.');
navigator.mediaDevices.getUserMedia (
// constraints - only audio needed for this app
{
audio: true
})
// Success callback
.then(function(stream) {
var mediaRecorder = new MediaRecorder(stream);
record.onclick = function() {
mediaRecorder.start();
record.disabled = true;
stop.disabled = false;
console.log(mediaRecorder.state);
console.log("recorder started");
record.style.background = "red";
record.style.color = "black";
}
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
chunks.push(e.data);
}
stop.onclick = function() {
mediaRecorder.stop();
record.disabled = false;
stop.disabled = true;
console.log(mediaRecorder.state);
console.log("recorder stopped");
record.style.background = "";
record.style.color = "";
}
mediaRecorder.onstop = function(e) {
console.log("recorder stopped");
var audio = document.querySelector('#audio');
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
chunks = [];
var audioURL = window.URL.createObjectURL(blob);
$("#source").attr("src", audioURL);
$("#audio")[0].load();
stream.getTracks()[0].stop();
//CODE TO UPLOAD BLOB DATA TO DJANGO SERVER
?????????
//
}
})
// Error callback
.catch(function(err) {
console.log('The following getUserMedia error occured: ' + err);
}
); } else {
console.log('getUserMedia not supported on your browser!'); }
對於一個小時的錄制,當前設置是否可以正常工作? 如果有更好的方式在客戶端錄制音頻並將其上傳到服務器,我將不勝感激。
您可以使用JQuery Ajax將Blob數據發送到Django服務器
var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
console.log("start sending binary data...");
var form = new FormData();
form.append('audio', blob);
$.ajax({
url: 'http://localhost:8000/<your api endpoint>/',
type: 'POST',
data: form,
processData: false,
contentType: false,
success: function (data) {
console.log('response' + JSON.stringify(data));
},
error: function () {
// handle error case here
}
});
在Django視圖中,您可以輕松地使用
audio_data = request.FILES['audio']
# you can directly assign audio_data to FileField model attribute
注意:如果數據不是很大(超過服務器超時),則上述代碼可以正常工作
如果文件真的很大,我建議您使用tus協議上傳文件
這種方法使您可以分塊上傳大型文件。 對於Django項目,您可以使用django-tus包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.