uniapp在H5端如何调用摄像头录制视频

在uniapp开发H5页面时,如何调用摄像头实现视频录制功能?需要兼容主流浏览器,希望能提供具体的代码示例和权限配置方法。另外,录制完成后如何获取视频文件并上传到服务器?

2 回复

在H5端,使用uniapp的<camera>组件或uni.chooseVideo API调用摄像头录制视频。需注意浏览器兼容性,建议使用HTTPS协议。


在 UniApp 的 H5 端调用摄像头录制视频,可以使用 HTML5 的 getUserMedia API 结合 <video><input type="file"> 元素实现。以下是具体步骤和代码示例:

方法一:使用 getUserMedia API(适用于现代浏览器)

  1. 请求摄像头权限:通过 navigator.mediaDevices.getUserMedia 获取视频流。
  2. 显示视频预览:将视频流绑定到 <video> 元素。
  3. 录制视频:使用 MediaRecorder API 录制并保存视频。
<template>
  <view>
    <video ref="videoRef" autoplay muted></video>
    <button @click="startRecording">开始录制</button>
    <button @click="stopRecording">停止录制</button>
    <video v-if="videoUrl" :src="videoUrl" controls></video>
  </view>
</template>

<script>
export default {
  data() {
    return {
      mediaRecorder: null,
      recordedChunks: [],
      videoUrl: ''
    };
  },
  methods: {
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
        this.$refs.videoRef.srcObject = stream;
        this.mediaRecorder = new MediaRecorder(stream);
        this.recordedChunks = [];

        this.mediaRecorder.ondataavailable = (event) => {
          if (event.data.size > 0) {
            this.recordedChunks.push(event.data);
          }
        };

        this.mediaRecorder.onstop = () => {
          const blob = new Blob(this.recordedChunks, { type: 'video/mp4' });
          this.videoUrl = URL.createObjectURL(blob);
          stream.getTracks().forEach(track => track.stop()); // 释放摄像头
        };

        this.mediaRecorder.start();
      } catch (error) {
        console.error('无法访问摄像头:', error);
      }
    },
    stopRecording() {
      if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
        this.mediaRecorder.stop();
      }
    }
  }
};
</script>

方法二:使用 <input type="file">(简单兼容方案)

通过文件输入调用设备摄像头(移动端支持):

<template>
  <view>
    <input type="file" accept="video/*" capture="environment" @change="handleVideoUpload">
    <video v-if="videoUrl" :src="videoUrl" controls></video>
  </view>
</template>

<script>
export default {
  data() {
    return {
      videoUrl: ''
    };
  },
  methods: {
    handleVideoUpload(event) {
      const file = event.target.files[0];
      if (file) {
        this.videoUrl = URL.createObjectURL(file);
      }
    }
  }
};
</script>

注意事项:

  • 兼容性getUserMedia 需 HTTPS 环境(本地 localhost 除外)。
  • 用户授权:首次使用需用户允许摄像头权限。
  • 格式支持:不同浏览器对视频格式支持可能不同(如 Chrome 支持 MP4)。
  • UniApp 限制:H5 端无法直接使用原生组件(如 camera),需用 HTML5 API。

选择方法一可自定义录制过程,方法二更简单但功能有限。根据需求选择即可。

回到顶部