使用 MediaRecorder 我从网络摄像头存储视频,然后通过 AJAX 调用将数据发送到我的 django 后端。但数据已损坏

问题描述 投票:0回答:0

我使用 MediaRecorder 存储来自网络摄像头的视频,然后通过 AJAX 调用将数据发送到我的 django 后端。他们的 im 以(mp4 或 webM)格式存储视频。问题是存储的视频已损坏,因为除了 VLC 播放器之外没有其他人正在运行文件。主要问题是我将此视频发送到 python 代码,然后从视频中提取音频。要执行此 pyhton 脚本,首先需要视频持续时间来处理它。由于文件损坏,VLC 文件正在运行,但持续时间栏未显示任何内容。所以,我认为数据没有按照我想要的方式存储。

我是 django 的新手,特别是前端,所以请帮助我。建议我任何替代方案,我只想正确存储我的视频,视频也有一个音频参数。我单独发送音频,所以我以某种方式绕过了从视频文件中提取音频的 python 脚本。但是使用 AJAX 发送的音频是空的,或者我认为是损坏的。

这是前端的JS代码。

const preview = document.getElementById("preview");
        const startButton = document.getElementById("startButton");
        const stopButton = document.getElementById("stopButton");
        const recorded = document.getElementById("recorded");
        const saveButton = document.getElementById("saveButton");
        const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        let mediaRecorder;
        let recordedVideoChunks = [];
        let recordedAudioChunks = [];

        navigator.mediaDevices.getUserMedia({
            audio: true,
            video: true
          }).then(stream => {
            preview.srcObject = stream;
            preview.play();
            mediaRecorder = new MediaRecorder(stream, {
              mimeType: 'video/webm;codecs=vp9,opus'
            });
            mediaRecorder.ondataavailable = function(e) {
              if (e.data && e.data.size > 0) {
                if (e.data.type.indexOf('video') !== -1) {
                  recordedVideoChunks.push(e.data);
                } else if (e.data.type.indexOf('audio') !== -1) {
                  recordedAudioChunks.push(e.data);
                }
              }
            };
            mediaRecorder.onstop = function() {
              const videoBlob = new Blob(recordedVideoChunks, {type: 'video/webm'});
              const audioBlob = new Blob(recordedAudioChunks, {type: 'audio/webm'});
              recorded.src = URL.createObjectURL(videoBlob);
              recorded.controls = true;
              saveButton.disabled = false;
              stream.getTracks().forEach(function(track) {
                track.stop();
              });

            };
          });

        startButton.addEventListener("click", () => {
          recordedVideoChunks = [];
          recordedAudioChunks = [];
          mediaRecorder.start();
          startButton.disabled = true;
          stopButton.disabled = false;
          saveButton.disabled = true;
        });

        stopButton.addEventListener("click", () => {
          mediaRecorder.stop();
          startButton.disabled = false;
          stopButton.disabled = true;
          preview.srcObject.getTracks().forEach(track => track.stop()); // stop camera and mic
          preview.hidden = true; // hide preview video element
        });

        saveButton.addEventListener("click", () => {
          const formData = new FormData();
          formData.append("csrfmiddlewaretoken", csrfToken);
          formData.append("video", new Blob(recordedVideoChunks, {type: 'video/webm'}));
          formData.append("audio", new Blob(recordedAudioChunks, {type: 'audio/webm'}));
          $.ajax({
            url: "http://localhost:7000/vedio/",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function() {
              alert("Video saved successfully.");
            },
            error: function() {
              alert("Error saving video.");
            }
          });
        });

Django 用于存储视频的后端代码

if request.method == 'POST':
        video_file = request.FILES.get('video')
        audio_file = request.FILES.get('audio')
        if not video_file or not audio_file:
            return HttpResponseBadRequest('Video or audio file is missing.')
        try:
            with open('output.webm', 'wb') as output:
                for chunk in video_file.chunks():
                    output.write(chunk)
                for chunk in audio_file.chunks():
                    output.write(chunk)
            return HttpResponse('Video saved successfully.')
        except Exception as e:
            return HttpResponseServerError('Error saving video: ' + str(e))

html django ajax mediarecorder
© www.soinside.com 2019 - 2024. All rights reserved.