vue3 + webrtc 實(shí)現(xiàn)視頻錄制功能

記錄一下vue3 使用 webrtc 調(diào)用攝像頭進(jìn)行錄像并保存file文件到后端,最后有效果圖

調(diào)用 getUserMedia API 需要在https或者localhost協(xié)議下
頁(yè)面全代碼, 直接復(fù)制可使用。
<template>
  <div style="background-color: #ffffff;padding-top:200px;">
    <div class="video-box">
      <video ref="video" webkit-playsinline playsinline :controls="false" muted class="video"></video>
    </div>
    <div class="checkagain" @click="startRecord">開(kāi)始錄制</div>
  </div>
</template>
<script>
import { reactive, ref, onMounted } from "vue"
export default {
  name: "v-video",
  setup(props, context) {
    const state = reactive({
      mediaRecorder: {},
      recorderFile: {},
      stream: {},
      stopRecordCallback: null
    })

    const video = ref(null)
    
    onMounted(() => {
      openCamera()
    })

    const openCamera = () => {
      getUserMedia(function(error, stream) {
        if (error) {
          console.log(error)
        } else {
          let options = { mimeType: 'video/webm;codecs=vp9,opus' }
          if (!MediaRecorder.isTypeSupported(options.mimeType)) {
            console.log(`${options.mimeType} is not supported`)
            options = { mimeType: 'video/webmcodecs=vp8,opus' }
            if (!MediaRecorder.isTypeSupported(options.mimeType)) {
              console.log(`${options.mimeType} is not supported`)
              options = { mimeType: 'video/webm' }
              if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                console.log(`${options.mimeType} is not supported`)
                options = { mimeType: '' }
              }
            }
          }
          state.mediaRecorder = new MediaRecorder(stream, options)
          state.stream = stream
          // 存儲(chǔ)數(shù)據(jù)流
          let chunks = []
          video.value.srcObject = stream
          video.value.play()
          state.mediaRecorder.ondataavailable = e => {
            state.mediaRecorder.blobs.push(e.data)
            chunks.push(e.data)
          }
          state.mediaRecorder.blobs = []
          state.mediaRecorder.onstop = () => {
            // 數(shù)據(jù)流轉(zhuǎn)換為 file
            state.recorderFile = getRecorderFile(chunks)
          }
        }
      })
    }

    const getRecorderFile = chunks => {
      const blob = new Blob(chunks, { type: state.mediaRecorder.mimeType })
      const file = new File([blob], 'media_.mp4')
      return file
    }

    const getUserMedia = callback => {
      const constraints = { // 表示同時(shí)采集視頻金和音頻
        video : {
          width: 400,   // 寬帶
          height: 400,  // 高度
          frameRate: 15, // 幀率
          facingMode: 'user', //  設(shè)置為前置攝像頭
        }, 
        audio : true // 將聲音獲取設(shè)為true
      }
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        callback(new Error('您的瀏覽器暫不支持視頻錄制'))
      } else {
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function(stream) {
            callback(false, stream)
          })
          .catch(function(error) {
            callback(error)
          })
      }
    }
    // 開(kāi)始錄制
    const startRecord = () => {
      state.mediaRecorder.start() // start方法里面?zhèn)魅胍粋€(gè)時(shí)間片,每隔一個(gè) 時(shí)間片存儲(chǔ) 一塊數(shù)據(jù)
      setTimeout(() => {
        stopRecord(state.stream);
      }, 3 * 1000)
    }

    // 停止錄制
    const stopRecord = stream => {
      state.mediaRecorder.stop()
      closeStream(stream)
    }
    // 關(guān)閉流
    const closeStream = stream => {
      const tracks = stream.getTracks()
      tracks.forEach(track => {
        track.stop()
      })
    }

    return {
      state,
      video,
      startRecord
    }
  }
  
}
</script>
<style scoped lang="scss">
.checkagain {
  background-color: #f44242;
  height: 35px;
  position: fixed;
  width: 90%;
  margin-left: 5%;
  transform: translateY(2.5%);
  border-radius: 3px;
  font-size: 14px;
  text-align: center;
  line-height: 35px;
  bottom: 35px;
  color: #ffffff;
}
.video-box {
  width: 200px;
  height: 200px;
  border-radius: 100%;
  margin-left: calc((100% - 200px) / 2);
  -webkit-mask-image: -webkit-radial-gradient(circle, white 100%, black 100%);
  -webkit-transform: rotate(0.000001deg); 
  -webkit-border-radius: 100%; 
  -moz-border-radius: 100%;
  .video {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    object-fit: cover;
  }
}
</style>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容