electron 响应式MediaStream对象上不存在属性“srcObject”

hk8txs48  于 10个月前  发布在  Electron
关注(0)|答案(1)|浏览(134)

我目前正在尝试访问我的网络摄像头在电子/ vuejs / vitejs应用程序,一切似乎都工作得很好(我可以访问我的网络摄像头在应用程序)但vs代码JS是抱怨“属性'srcObject'不存在类型'{只读活动:布尔;只读ID:字符串; onaddtrack:((这:MediaStream,ev:MediaStreamTrackEvent)=>任何)|null; onremovetrack:((this:MediaStream,ev:MediaStreamTrackEvent)=> any)|null;. 9 more.; dispatchEvent:(event:Event)=> boolean;}'.”
你知道我该怎么解决吗?

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

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

let vid = reactive<MediaStream>(new MediaStream);

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

onMounted(async () => {
  //Get all mediaDevices attached to the computer
  let devices = await navigator.mediaDevices.enumerateDevices();

  //Iterate over all of the devices
  for (let index = 0; index < devices.length; index++) {
    const device = devices[index];
    if (device.kind == "videoinput") {
      //Add the video device because it is a videoDevice. Manually create a new object with device details instead of passing device.
      videoDevices.push({
        deviceId: device.deviceId,
        kind: device.kind,
        label: device.label,
      });
    }
  }
  if (videoDevices && videoDevices.length > 0) {
    deviceID.value = videoDevices[0].deviceId
    console.log(devices[0].label)
  }
});

watch(deviceID,  async (newDeviceId, oldDeviceId) => {
  //Start the video with the exact deviceId we are trying to observe
  var constraints = {
    deviceId: { exact: newDeviceId },
  };

  //Create a stream with the webcam selected by the constraints above.
  let stream = await navigator.mediaDevices.getUserMedia({
    video: constraints,
  });

  //Set the source to be the stream we are capturing above
  vid.srcObject = stream;
 
  //When the stream is loaded, begin playing the stream
  vid.onloadedmetadata = async function() {
    const err = await  vid.play();
    console.log(err);
  };
});
</script>

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

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

字符串
谢谢你,谢谢

hxzsmxv2

hxzsmxv21#

这个错误来自TypeScript执行其强制类型的工作。您已经将vid声明为MediaStream对象。

let vid = reactive<MediaStream>(new MediaStream);

字符串
MediaStream没有记录srcObject属性,因此出现错误。实际上,srcObject本身就是MediaStream对象。看起来你应该将vid定义为HTMLVideoElement。这种类型匹配代码中看到的所有属性和函数。
vid初始化代码更新为:

const vid = reactive<HTMLVideoElement>(new HTMLVideoElement())


另外,请将所有reactiveref变量的let更新为const,因为这些是React对象,不应该被重新分配(只有它们的内部值根据Vue documentation变化)。

相关问题