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

Electron+Angular13中getUserMedia传入MediaStreamConstraints报错

Electron+Angular13录屏功能:getUserMedia类型不兼容问题解决

问题原因

Angular项目里的TypeScript用的是标准DOM类型定义,不包含Electron特有的chromeMediaSource这类私有约束字段,所以直接照搬纯Electron的代码会触发类型校验错误。

解决方案

1. 类型断言快速绕过检查

最直接的方式是把约束对象断言为any类型,跳过TypeScript的类型检查:

let constraints = {
    audio: false,
    video: {
        mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: displayId
        }
    }
};

let stream = await navigator.mediaDevices.getUserMedia(constraints as any);

2. 扩展TypeScript类型定义(更优雅)

在项目根目录创建一个类型声明文件(比如electron-media.d.ts),扩展原生的MediaStreamConstraints类型,让TypeScript识别Electron特有的字段:

interface ElectronTrackConstraints {
    mandatory?: {
        chromeMediaSource?: string;
        chromeMediaSourceId?: string;
    };
}

declare global {
    interface MediaStreamConstraints {
        video?: boolean | ElectronTrackConstraints;
    }
}

之后在tsconfig.json的include数组里添加这个文件,确保TypeScript能加载它。

3. 用Electron官方desktopCapturer API(推荐)

Electron官方更推荐使用desktopCapturer来获取屏幕流,避免依赖Chrome私有API,兼容性更好:

import { desktopCapturer } from 'electron';

// 获取所有可用的屏幕/窗口源
const sources = await desktopCapturer.getSources({ types: ['screen', 'window'] });
// 找到目标源(根据你的displayId匹配)
const targetSource = sources.find(source => source.id === displayId);

if (targetSource) {
    const constraints = {
        audio: false,
        video: {
            mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: targetSource.id,
                // 可按需添加分辨率约束
                minWidth: 1920,
                maxWidth: 1920,
                minHeight: 1080,
                maxHeight: 1080
            }
        } as any
    };
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    // 后续处理流(比如渲染到video元素)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:45:37