You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron/Vue3/Vite项目MediaStream无srcObject属性的TS报错求助

解决TypeScript提示“Property 'srcObject' does not exist on type 'MediaStream'”的问题

问题核心是你混淆了视频DOM元素和MediaStream媒体流对象的类型:你把vid声明为MediaStream类型,但模板里的<video>对应的是HTMLVideoElement,srcObject是视频元素的属性,并非MediaStream的成员,所以TypeScript会报错。

具体修正步骤:

  • 将vid改为使用Vue的ref来获取DOM元素,类型声明为HTMLVideoElement | null
  • 在操作视频元素前,先判断元素是否存在(避免空值报错)
  • 移除原本错误的reactive<MediaStream>声明

修正后的完整代码:

<script setup lang="ts">
import { onMounted, ref, watch, reactive } from 'vue'

interface Device {
  deviceId: string;
  label: string;
  kind: string
}

// 改为用ref获取video DOM元素,类型为HTMLVideoElement或null
const vid = ref<HTMLVideoElement | null>(null);

let deviceID = ref('');
let videoDevices = reactive<Device[]>([]);

onMounted(async () => {
  const devices = await navigator.mediaDevices.enumerateDevices();
  
  for (const device of devices) {
    if (device.kind === "videoinput") {
      videoDevices.push({
        deviceId: device.deviceId,
        kind: device.kind,
        label: device.label,
      });
    }
  }
  
  if (videoDevices.length > 0) {
    deviceID.value = videoDevices[0].deviceId;
  }
});

watch(deviceID, async (newDeviceId) => {
  const constraints = {
    deviceId: { exact: newDeviceId },
  };

  const stream = await navigator.mediaDevices.getUserMedia({
    video: constraints,
  });

  // 先判断video元素是否存在
  if (vid.value) {
    // 设置视频元素的srcObject
    vid.value.srcObject = stream;
    
    vid.value.onloadedmetadata = async function() {
      try {
        await this.play();
      } catch (err) {
        console.error('播放失败:', err);
      }
    };
  }
});
</script>

<template>
  <video ref="vid" />
  <select v-model="deviceID" v-if="videoDevices.length >= 1" style="border:1px black solid">
    <option v-for="device in videoDevices" :key="device.deviceId" :value="device.deviceId">
        {{ device.label }}
    </option>
  </select>  
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>

额外优化点:

  • 用for...of替代传统for循环,代码更简洁
  • 给play()添加try/catch捕获播放异常
  • 移除不必要的videoDevices &&判断(因为reactive数组默认是空数组,length判断足够)

内容的提问来源于stack exchange,提问作者thomas sauzeau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 05:15:31