简体   繁体   English

给定Blob网址后,如何将大型音频文件上传到Django服务器?

[英]How to upload large audio file to a django server given a blob url?

I've got a javascript that records audio using MediaRecorder and pushes the binary data into an array chunk . 我有一个JavaScript,它使用MediaRecorder记录音频并将二进制数据推送到数组chunk Once the user finishes recording, the data is converted into a blob and loaded to an HTML's audio element for playback. 用户完成记录后,数据将转换为blob并加载到HTML的audio元素中进行播放。 My issue is now trying to load this data onto the Django server at the same time. 我的问题是现在尝试将这些数据同时加载到Django服务器上。 Most sample upload script I've seen has users manually loading an audio file into a form's input element and manually hitting a submit button, but my data is already loaded into a blob file so I am not sure how to proceed. 我见过的大多数示例上传脚本都让用户手动将音频文件加载到表单的input元素中,并手动单击提交按钮,但是我的数据已经加载到Blob文件中,因此我不确定如何继续。

HTML 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 使用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!');   }

Would the current setup work well for an hour-long recording? 对于一个小时的录制,当前设置是否可以正常工作? If there are any better way of recording audio on the client side and uploading it to server I would greatly appreciate any guidence. 如果有更好的方式在客户端录制音频并将其上传到服务器,我将不胜感激。

You can use JQuery Ajax to send blob data to Django server 您可以使用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
    }
});

And in Django view, you can easily retrieve blob using 在Django视图中,您可以轻松地使用

audio_data = request.FILES['audio']
# you can directly assign audio_data to FileField model attribute

Note: Above code will work fine if the data is not that large, which exceeds your server timeout 注意:如果数据不是很大(超过服务器超时),则上述代码可以正常工作


If the file is really large then I will recommend you to upload your file using tus protocol 如果文件真的很大,我建议您使用tus协议上传文件

This approach offers you to upload a large file in chunks. 这种方法使您可以分块上传大型文件。 For the Django project, you can use django-tus package. 对于Django项目,您可以使用django-tus包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM