国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Vue調用攝像頭錄制視頻和音頻并上傳給后端或下載到本地

這篇具有很好參考價值的文章主要介紹了Vue調用攝像頭錄制視頻和音頻并上傳給后端或下載到本地。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

下載插件

npm install --save webm-duration-fix

代碼及作用

調用攝像頭


callCamera () {
        let _this = this;
        MediaUtils.getUserMedia(true, true, function (err, stream) {
          if (err) {
            throw err;
          } else {
            // 通過 MediaRecorder 記錄獲取到的媒體流
            const mimeType = 'video/webm;codecs=vp8,opus';
            mediaRecorder = new MediaRecorder(stream, {
              // mimeType: "video/webm;codecs=vp9",
              mimeType: mimeType,
            });
            mediaStream = stream;
            var chunks = []
            var video = _this.$refs.videos;
            video["srcObject"] = stream;
            video.play();// 播放實時畫面
            mediaRecorder.ondataavailable = function (e) {
              mediaRecorder.blobs.push(e.data);
              chunks.push(e.data);
            };
            mediaRecorder.blobs = [];

            mediaRecorder.onstop = async () => {
              recorderFile = await fixWebmDuration(new Blob(chunks, { type: mimeType }));
              console.log(recorderFile);
              var url = URL.createObjectURL(recorderFile)
              var videosreplay = _this.$refs.videosreplay;
              videosreplay.setAttribute("src", url);
              console.log('url', url)
              chunks = [];
              if (null != stopRecordCallback) {
                stopRecordCallback();
              }
            };
            _this.record()
          }
        });
      },

開始結束錄制

record () {
        if (this.recordtype == "ING") {
          this.stopRecord(() => {
            console.log("結束錄制");
            this.toggleReplayVideo()
          });
        }
        else if (this.recordtype == "BEGIN") {
          console.log("開始錄制");
          this.startAudio();
          mediaRecorder.start();
          startTime = Date.now();
          this.recordtype = "ING";
        }
      },

對錄像時長進行記錄


      startAudio () {
        this.timer = setInterval(() => {
          this.recordtime += 1000;
          if (this.recordtime == 1000000) {
            this.stopRecord();
          }
          this.second++;
          if (this.second >= 60) {
            this.second = 0;
            this.minute = this.minute + 1;
          }

          if (this.minute >= 60) {
            this.minute = 0;
            this.hour = this.hour + 1;
          }
          console.log(this.recordtime)
        }, 1000);
      },

停止錄像時終止錄制器,關閉媒體流并清除時長記錄定時器

      stopRecord (callback) {
        this.recordtype = "END";
        this.showReplay = true;
        stopRecordCallback = callback;
        clearInterval(this.timer);
        // 終止錄制器
        mediaRecorder.stop();
        // 關閉媒體流
        MediaUtils.closeStream(mediaStream);
        var videosreplay = this.$refs.videosreplay;
        videosreplay.onended = () => {
          this.playtime = 0;
          this.replayVideo = false;
          clearInterval(this.playtimer);
        };
        videosreplay.onclick = () => {
          this.showReplay = !this.showReplay;
        };
      },

回放

      toggleReplayVideo () {
        console.log('播放中...')
        this.replayVideo = !this.replayVideo;
        this.showReplay = false;
        var videosreplay = this.$refs.videosreplay;
        if (this.replayVideo) {
          videosreplay.play().catch(err => {
            this.$message.error(err.message);
            console.log(err);
          });
          this.playtimer = setInterval(() => {
            this.playtime += 1000;
          }, 1000);
        } else {
          videosreplay.pause();
          clearInterval(this.playtimer);
        }
      },

下載視頻

指定且只能指定,下載后的默認文件名字和文件后綴。注意,可以不指定后綴名,瀏覽器會根據(jù)數(shù)據(jù)類型自動為其匹配后綴名,但是最好指定后綴。

<a href="base64..." download="after">SAVE</a>

下載后的文件名為after.jpg
download屬性不能指定下載路徑;
當 download 屬性值為空時,下載的文件的名字和擴展名與源文件一致;當href為base64編碼的圖像數(shù)據(jù)時,則下載后文件名也是那么離譜得長。

<a href="base64..." download>SAVE</a>

下載后的文件名為data_image_jpeg;base64,… .jpg

      download () {
        var url = URL.createObjectURL(recorderFile)
        console.log("URLLLLLL", url)
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.style.display = "none";
        a.href = url;
        if (this.fileName) {
          a.download = this.fileName + ".mp4";
        } else {
          a.download = new Date() + ".mp4";
        }
        a.click();
        window.URL.revokeObjectURL(url);
      },

下載或上傳給后端

      submit () {
        let that = this;
        console.log(recorderFile)
        // 下載
        this.download()
        let file = new File(
          [recorderFile],
          "msr-" + new Date().toISOString().replace(/:|\./g, "-") + ".mp4",
          {
            type: "video/mp4",
          }
        );
        let config = {
          headers: { "Content-Type": "multipart/form-data" }
        }
        console.log('file', file)
        const formdata = new FormData()
        formdata.append("file", file);
        // 傳給后端
        // axios.post('/video', formdata, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },) //請求頭要為表單
        //   .then(response => {
        //     console.log('video', response.data);
        //     this.yy_score = parseInt(response.data.data + 0.5)
        //     that.progress = response.data.data * 1.0 / 23 * 100
        //   })
        //   .catch(function (error) {
        //     that.$message({
        //       message: error,
        //       type: 'error'
        //     });
        //     console.log(error);
        //   })
      },
var MediaUtils = {
    /**
     * 獲取用戶媒體設備(處理兼容的問題)
     * @param videoEnable {boolean} - 是否啟用攝像頭
     * @param audioEnable {boolean} - 是否啟用麥克風
     * @param callback {Function} - 處理回調
     */
    getUserMedia: function (videoEnable, audioEnable, callback) {
      navigator.getUserMedia =
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia ||
        window.getUserMedia;
      var constraints = { video: videoEnable, audio: audioEnable };
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            callback(false, stream);
          })
        ["catch"](function (err) {
          callback(err);
        });
      } else if (navigator.getUserMedia) {
        navigator.getUserMedia(
          constraints,
          function (stream) {
            callback(false, stream);
          },
          function (err) {
            callback(err);
          }
        );
      } else {
        callback(new Error("Not support userMedia"));
      }
    },

    /**
     * 關閉媒體流
     * @param stream {MediaStream} - 需要關閉的流
     */
    closeStream: function (stream) {
      if (typeof stream.stop === "function") {
        stream.stop();
      } else {
        let trackList = [stream.getAudioTracks(), stream.getVideoTracks()];

        for (let i = 0; i < trackList.length; i++) {
          let tracks = trackList[i];
          if (tracks && tracks.length > 0) {
            for (let j = 0; j < tracks.length; j++) {
              let track = tracks[j];
              if (typeof track.stop === "function") {
                track.stop();
              }
            }
          }
        }
      }
    },
  };
  var startTime, mediaRecorder, mediaStream, stopRecordCallback, recorderFile;

頁面完整代碼

<template>
  <div>
    <video id="video" autoplay ref="videos" style="width: 400px;height: 400px;" muted></video>
    <video style="width: 400px;height: 400px;" id="videosreplay" src="" ref="videosreplay"></video>
    <button @click="callCamera()">開始錄制</button>
    <button @click="record()">結束錄制</button>
    <button @click="submit()">下載或上傳</button>
  </div>
</template>
<script>
  import axios from 'axios'
  import fixWebmDuration from 'webm-duration-fix'

  export default {
    name: "Test",
    data () {
      return {
        progress: 0,
        replayVideo: false,
        recordtype: "BEGIN",
        showReplay: true,
        timer: 0,
        recordtime: 0,
        second: 0,
        minute: 0,
        hour: 0,
        playtime: 0,
        playtimer: 0,
        yy_score: 0,
        cnt_sum: 0,
        ansMaxTime: 0,
        ansBeginTime: 0,
        ansMaxBeginTime: 0,

      }
    },
    methods: {
      // 調用攝像頭
      callCamera () {
        let _this = this;
        MediaUtils.getUserMedia(true, true, function (err, stream) {
          if (err) {
            throw err;
          } else {
            // 通過 MediaRecorder 記錄獲取到的媒體流
            const mimeType = 'video/webm;codecs=vp8,opus';
            mediaRecorder = new MediaRecorder(stream, {
              // mimeType: "video/webm;codecs=vp9",
              mimeType: mimeType,
            });
            mediaStream = stream;
            var chunks = []
            var video = _this.$refs.videos;
            video["srcObject"] = stream;
            video.play();// 播放實時畫面
            mediaRecorder.ondataavailable = function (e) {
              mediaRecorder.blobs.push(e.data);
              chunks.push(e.data);
            };
            mediaRecorder.blobs = [];

            mediaRecorder.onstop = async () => {
              recorderFile = await fixWebmDuration(new Blob(chunks, { type: mimeType }));
              console.log(recorderFile);
              var url = URL.createObjectURL(recorderFile)
              var videosreplay = _this.$refs.videosreplay;
              videosreplay.setAttribute("src", url);
              console.log('url', url)
              chunks = [];
              if (null != stopRecordCallback) {
                stopRecordCallback();
              }
            };
            _this.record()
          }
        });
      },
      record () {
        if (this.recordtype == "ING") {
          this.stopRecord(() => {
            console.log("結束錄制");
            this.toggleReplayVideo()
          });
        }
        else if (this.recordtype == "BEGIN") {
          console.log("開始錄制");
          this.startAudio();
          mediaRecorder.start();
          startTime = Date.now();
          this.recordtype = "ING";
        }
      },

      // 對錄像時長進行記錄
      startAudio () {
        this.timer = setInterval(() => {
          this.recordtime += 1000;
          if (this.recordtime == 1000000) {
            this.stopRecord();
          }
          this.second++;
          if (this.second >= 60) {
            this.second = 0;
            this.minute = this.minute + 1;
          }

          if (this.minute >= 60) {
            this.minute = 0;
            this.hour = this.hour + 1;
          }
          console.log(this.recordtime)
        }, 1000);
      },

      // 停止錄像時終止錄制器,關閉媒體流并清除時長記錄定時器
      stopRecord (callback) {
        this.recordtype = "END";
        this.showReplay = true;
        stopRecordCallback = callback;
        clearInterval(this.timer);
        // 終止錄制器
        mediaRecorder.stop();
        // 關閉媒體流
        MediaUtils.closeStream(mediaStream);
        var videosreplay = this.$refs.videosreplay;
        videosreplay.onended = () => {
          this.playtime = 0;
          this.replayVideo = false;
          clearInterval(this.playtimer);
        };
        videosreplay.onclick = () => {
          this.showReplay = !this.showReplay;
        };
      },
      // 回放
      toggleReplayVideo () {
        console.log('播放中...')
        this.replayVideo = !this.replayVideo;
        this.showReplay = false;
        var videosreplay = this.$refs.videosreplay;
        if (this.replayVideo) {
          videosreplay.play().catch(err => {
            this.$message.error(err.message);
            console.log(err);
          });
          this.playtimer = setInterval(() => {
            this.playtime += 1000;
          }, 1000);
        } else {
          videosreplay.pause();
          clearInterval(this.playtimer);
        }
      },
      // 下載視頻
      download () {
        var url = URL.createObjectURL(recorderFile)
        console.log("URLLLLLL", url)
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.style.display = "none";
        a.href = url;
        if (this.fileName) {
          a.download = this.fileName + ".mp4";
        } else {
          a.download = new Date() + ".mp4";
        }
        a.click();
        window.URL.revokeObjectURL(url);
      },
      // 下載或上傳
      submit () {
        let that = this;
        console.log(recorderFile)
        // 下載
        this.download()
        let file = new File(
          [recorderFile],
          "msr-" + new Date().toISOString().replace(/:|\./g, "-") + ".mp4",
          {
            type: "video/mp4",
          }
        );
        let config = {
          headers: { "Content-Type": "multipart/form-data" }
        }
        console.log('file', file)
        const formdata = new FormData()
        formdata.append("file", file);
        // 傳給后端
        // axios.post('/video', formdata, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },) //請求頭要為表單
        //   .then(response => {
        //     console.log('video', response.data);
        //     this.yy_score = parseInt(response.data.data + 0.5)
        //     that.progress = response.data.data * 1.0 / 23 * 100
        //   })
        //   .catch(function (error) {
        //     that.$message({
        //       message: error,
        //       type: 'error'
        //     });
        //     console.log(error);
        //   })
      },
    }
  }
  var MediaUtils = {
    /**
     * 獲取用戶媒體設備(處理兼容的問題)
     * @param videoEnable {boolean} - 是否啟用攝像頭
     * @param audioEnable {boolean} - 是否啟用麥克風
     * @param callback {Function} - 處理回調
     */
    getUserMedia: function (videoEnable, audioEnable, callback) {
      navigator.getUserMedia =
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia ||
        window.getUserMedia;
      var constraints = { video: videoEnable, audio: audioEnable };
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            callback(false, stream);
          })
        ["catch"](function (err) {
          callback(err);
        });
      } else if (navigator.getUserMedia) {
        navigator.getUserMedia(
          constraints,
          function (stream) {
            callback(false, stream);
          },
          function (err) {
            callback(err);
          }
        );
      } else {
        callback(new Error("Not support userMedia"));
      }
    },

    /**
     * 關閉媒體流
     * @param stream {MediaStream} - 需要關閉的流
     */
    closeStream: function (stream) {
      if (typeof stream.stop === "function") {
        stream.stop();
      } else {
        let trackList = [stream.getAudioTracks(), stream.getVideoTracks()];

        for (let i = 0; i < trackList.length; i++) {
          let tracks = trackList[i];
          if (tracks && tracks.length > 0) {
            for (let j = 0; j < tracks.length; j++) {
              let track = tracks[j];
              if (typeof track.stop === "function") {
                track.stop();
              }
            }
          }
        }
      }
    },
  };
  var startTime, mediaRecorder, mediaStream, stopRecordCallback, recorderFile;
</script>

結果

錄制

vue3實現(xiàn)錄屏同時錄制音頻和視頻合并軌道為一個文件,前端,vue.js,音視頻,javascript

播放

vue3實現(xiàn)錄屏同時錄制音頻和視頻合并軌道為一個文件,前端,vue.js,音視頻,javascript

下載

vue3實現(xiàn)錄屏同時錄制音頻和視頻合并軌道為一個文件,前端,vue.js,音視頻,javascript

項目代碼

https://gitee.com/yuan-hongting/video文章來源地址http://www.zghlxwxcb.cn/news/detail-615417.html

到了這里,關于Vue調用攝像頭錄制視頻和音頻并上傳給后端或下載到本地的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • untiy 錄制網(wǎng)絡攝像頭視頻并保存到本地文件

    untiy 錄制網(wǎng)絡攝像頭視頻并保存到本地文件

    網(wǎng)絡攝像頭使用的是海康威視的,關于如何使用Ump插件播放??低時tsp視頻流,請參考我的這篇文章 內部有ump插件的下載鏈接 untiy接入 ??低暰W(wǎng)絡攝像頭 錄屏使用的插件是 AVPro movieCapture 4.6.3版, 插件和完整工程的下載鏈接放在本文的最后 錄制攝像頭的實現(xiàn)思想為 1 um

    2023年04月09日
    瀏覽(21)
  • C#使用OpenCv(OpenCVSharp)使用攝像頭視頻顯示和錄制及圖片保存、本地視頻顯示

    本篇實例講解基于OpenCvSharp實現(xiàn)了攝像頭視頻顯示、錄制及截圖、視頻保存,本地視頻的顯示功能。 目錄 創(chuàng)建winform項目添加控件 NuGet安裝opencvsharp ?代碼 ?運行效果 實例實現(xiàn)過程

    2024年02月15日
    瀏覽(28)
  • javacv基礎02-調用本機攝像頭并預覽攝像頭圖像畫面視頻

    javacv基礎02-調用本機攝像頭并預覽攝像頭圖像畫面視頻

    引入架包: 運行效果: 注意: 1、maven依賴后,會導致整個項目工程打包發(fā)布后的體積變得十分巨大 原因是ffmpeg和opencv兩個依賴默認會把android,ios,linux,macos,windows以及各自不同cpu芯片下,86/64等所有版本的Jar會全部依賴進來,項目打包后體積劇增500M+ 解決方法也比較簡單

    2024年02月11日
    瀏覽(31)
  • 攝像頭的調用和視頻識別

    攝像頭的調用和視頻識別

    創(chuàng)建視頻捕捉對象:cv2.VideoCapture() 參數(shù)為視頻設備的索引號,就一個攝像投的話寫0默認; 或者是指定要讀取視頻的路徑。 cv2.VideoWriter() 通過對視頻中相鄰兩幀圖像做差分運算來標記運動物體, 移動的物體在相鄰幀中灰度會有差別,因此差值為0的是靜態(tài)物體。 飄動的彩帶也

    2024年02月11日
    瀏覽(29)
  • 使用OpenCV調用攝像頭和讀取視頻圖片

    使用OpenCV調用攝像頭和讀取視頻圖片

    要捕獲視頻,你需要創(chuàng)建一個 VideoCapture 對象。它的參數(shù)是設備索引的名稱。設備索引就是指定哪個攝像頭的數(shù)字。正常情況下,內部攝像頭可以通過傳入0來調用,傳遞1來選擇外置的第二個相機,以此類推。在此之后,你可以逐幀捕獲。但是在最后,不要忘記釋放俘虜。 直

    2024年02月08日
    瀏覽(28)
  • JavaScript音視頻,使用JavaScript如何在瀏覽器錄制電腦攝像頭畫面為MP4視頻文件并下載視頻文件到本地

    本章介紹使用JavaScript如何在瀏覽器錄制電腦攝像頭畫面為MP4視頻文件并下載視頻文件到本地。 1、使用navigator.mediaDevices.getUserMedia獲取攝像頭畫面 2、將獲取到的攝像頭畫面渲染到canvas畫板上 3、將canvas轉換為blob對象 4、通過document.createElement(‘a’)調用 href 方法獲取此鏈接并觸

    2024年02月02日
    瀏覽(31)
  • yolo v5代碼運行圖片、調用攝像頭、視頻

    yolo v5代碼運行圖片、調用攝像頭、視頻

    一、運行 1.視頻 修改detect文件219行。 default=ROOT / \\\'data/images/3.mp4\\\' 2.調用攝像頭 修改detect文件219行 3.圖片 修改detect文件219行。 default=ROOT / \\\'data/images/3.jpg\\\' 二、庫 Package Version absl-py 1.3.0 alabaster 0.7.12 applaunchservices 0.2.1 appnope 0.1.2 arrow 1.2.3 astroid 2.11.7 atomicwrites 1.4.0 attrs 22.1.0 autope

    2023年04月17日
    瀏覽(21)
  • JS PC端調用攝像頭錄視頻截圖上傳文件

    創(chuàng)建 Catcher 類 直接在HTML文件中調用

    2024年02月10日
    瀏覽(27)
  • vue調用電腦端攝像頭實時拍照

    vue調用電腦端攝像頭實時拍照

    點擊照相機拍照,彈出照相機拍照彈窗,點擊拍照按鈕,截取錄像的幀,點擊保存,提交數(shù)據(jù)給后臺。 1.html模塊 2.css模塊 就是一個彈窗,這里就不進行展示了。 3.js模塊

    2024年02月12日
    瀏覽(25)
  • Vue2調用電腦攝像頭權限,并拍照

    電腦端需要調取用戶攝像頭進行拍照

    2024年02月10日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包