简体   繁体   中英

unable to send audio file in django backend

I am trying to get the recorded audio file from the HTML to my Django backend but getting MultiValueDictKeyError at /audiomarge/ 'ouraudio'

here is my script

<script>
                    // set up basic variables for app

                    const record = document.querySelector('.record');
                    const stop = document.querySelector('.stop');
                    const soundClips = document.querySelector('.sound-clips');
                    const canvas = document.querySelector('.visualizer');
                    const mainSection = document.querySelector('.main-controls');

                    var x = document.getElementById("myAudio");

                    // disable stop button while not recording

                    stop.disabled = true;

                    // visualiser setup - create web audio api context and canvas

                    let audioCtx;
                    const canvasCtx = canvas.getContext("2d");

                    //main block for doing the audio recording

                    if (navigator.mediaDevices.getUserMedia) {
                        console.log('getUserMedia supported.');

                        const constraints = { audio: true };
                        let chunks = [];

                        let onSuccess = function (stream) {
                            const mediaRecorder = new MediaRecorder(stream);

                            visualize(stream);

                            record.onclick = function () {
                                x.play();
                                mediaRecorder.start();
                                console.log(mediaRecorder.state);
                                console.log("recorder started");
                                record.style.background = "red";

                                stop.disabled = false;
                                record.disabled = true;
                            }

                            stop.onclick = function () {
                                x.pause();
                                mediaRecorder.stop();
                                console.log(mediaRecorder.state);
                                console.log("recorder stopped");
                                record.style.background = "";
                                record.style.color = "";
                                // mediaRecorder.requestData();

                                stop.disabled = true;
                                record.disabled = false;
                            }

                            mediaRecorder.onstop = function (e) {
                                console.log("data available after MediaRecorder.stop() called.");

                                const clipName = prompt('Enter a name for your sound clip?', 'My unnamed clip');

                                const clipContainer = document.createElement('article');
                                const clipLabel = document.createElement('p');
                                const audio = document.createElement('audio');
                                const deleteButton = document.createElement('button');
                                const margeButton = document.createElement('button');

                                clipContainer.classList.add('clip');
                                audio.setAttribute('controls', '');
                                
                                deleteButton.textContent = 'Delete';
                                deleteButton.className = 'delete';
                                margeButton.textContent = 'Marge & Download';
                                margeButton.id = 'margebutton';
                             

                                if (clipName === null) {
                                    clipLabel.textContent = 'My unnamed clip';
                                } else {
                                    clipLabel.textContent = clipName;
                                }

                                clipContainer.appendChild(audio);
                                clipContainer.appendChild(clipLabel);
                                clipContainer.appendChild(deleteButton);
                                clipContainer.appendChild(margeButton);
                                soundClips.appendChild(clipContainer);

                                audio.controls = true;
                                const blob = new Blob(chunks, { 'type': 'audio/ogg; codecs=opus' });
                                chunks = [];
                                const audioURL = window.URL.createObjectURL(blob);
                                audio.src = audioURL;
                                console.log("recorder stopped");

                                deleteButton.onclick = function (e) {
                                    let evtTgt = e.target;
                                    evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
                                }
                                margeButton.onclick = function () {
                                    audio.id = 'ouraudio';
                                    audio.name = 'ouraudio';
                                    form.submit();
                                }

                                clipLabel.onclick = function () {
                                    const existingName = clipLabel.textContent;
                                    const newClipName = prompt('Enter a new name for your sound clip?');
                                    if (newClipName === null) {
                                        clipLabel.textContent = existingName;
                                    } else {
                                        clipLabel.textContent = newClipName;
                                    }
                                }
                            }

                            mediaRecorder.ondataavailable = function (e) {
                                chunks.push(e.data);
                            }
                        }

                        let onError = function (err) {
                            console.log('The following error occured: ' + err);
                        }

                        navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);

                    } else {
                        console.log('getUserMedia not supported on your browser!');
                    }

                    function visualize(stream) {
                        if (!audioCtx) {
                            audioCtx = new AudioContext();
                        }

                        const source = audioCtx.createMediaStreamSource(stream);

                        const analyser = audioCtx.createAnalyser();
                        analyser.fftSize = 2048;
                        const bufferLength = analyser.frequencyBinCount;
                        const dataArray = new Uint8Array(bufferLength);

                        source.connect(analyser);
                        //analyser.connect(audioCtx.destination);

                        draw()

                        function draw() {
                            const WIDTH = canvas.width
                            const HEIGHT = canvas.height;

                            requestAnimationFrame(draw);

                            analyser.getByteTimeDomainData(dataArray);

                            canvasCtx.fillStyle = 'rgb(200, 200, 200)';
                            canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

                            canvasCtx.lineWidth = 2;
                            canvasCtx.strokeStyle = 'rgb(0, 0, 0)';

                            canvasCtx.beginPath();

                            let sliceWidth = WIDTH * 1.0 / bufferLength;
                            let x = 0;


                            for (let i = 0; i < bufferLength; i++) {

                                let v = dataArray[i] / 128.0;
                                let y = v * HEIGHT / 2;

                                if (i === 0) {
                                    canvasCtx.moveTo(x, y);
                                } else {
                                    canvasCtx.lineTo(x, y);
                                }

                                x += sliceWidth;
                            }

                            canvasCtx.lineTo(canvas.width, canvas.height / 2);
                            canvasCtx.stroke();

                        }
                    }

                    window.onresize = function () {
                        canvas.width = mainSection.offsetWidth;
                    }

                    window.onresize();
                </script>

and my form is

<form method="post" action="/audiomarge/" enctype="multipart/form-data">
            {% csrf_token %}
            <input type="hidden" name="songname" id="songname" value={{song.slug}}>
                <section class="sound-clips">

                </section>

            </form>

and my views.py

def audiomarge(request):
    if request.POST:
        songname = request.GET.get('songname')
        ouraudio = request.FILES['ouraudio']
        return HttpResponse('working')

I am trying to get the recorded audio file from the HTML to my Django backend but getting MultiValueDictKeyError at /audiomarge/ 'ouraudio'

Below the line console.log("recorder stopped");

Add something along these lines:

var formData = new FormData();
var songname = document.getElementById("songname").value;
formData.append('ouraudio', blob);
formData.append('songname', songname);
$.ajax('/audiomarge/', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
});

and it will auto submit the blob upon recording stop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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