All
PC硬件
经验记录
生活杂谈
日常踩坑
前端技术
测试
2025-08-08
经验记录
react
react-native
electron
5
最近项目中的新接触
  1. 前端录屏功能
  • 使用rtcRecorder对视频流进行录制。
  • 指定区域录制,使用canvas对视频帧进行截取,然后录制canvas流。
  • 录屏功能electron应用中实现。
// 主进程中使用desktopCapturer
  session.defaultSession.setDisplayMediaRequestHandler(
    (_, callback) => {
      desktopCapturer.getSources({ types: ['window'] }).then((sources) => {
        // Grant access to the first screen found.
        callback({ video: sources[0], audio: 'loopback' })
      })
      // If true, use the system picker if available.
      // Note: this is currently experimental. If the system picker
      // is available, it will be used and the media request handler
      // will not be invoked.
    },
    { useSystemPicker: true }
  )
  
// 渲染进程中
export const useDisplayMedia = (options: UseDisplayMediaOptions) => {
  const { onStream } = options
  const [stream, setStream] = useState<MediaStream | null>(null)
  const streamRef = useRef<MediaStream | null>(null)
  const onStreamRef = useRef(onStream)

  useEffect(() => {
    navigator.mediaDevices
      .getDisplayMedia({
        audio: true,
        video: {
          width: { ideal: 1920 },
          height: { ideal: 1080 },
          frameRate: { ideal: 60, max: 60 }
        }
      })
      .then((mediaStream) => {
        streamRef.current = mediaStream
        setStream(mediaStream)
        onStreamRef.current?.(mediaStream)
        // 打印实际分辨率
        const track = mediaStream.getVideoTracks()[0]
        console.log('实际分辨率:', track.getSettings())
      })
      .catch((e) => {
        console.error('获取媒体流失败:', e)
      })

    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach((track) => track.stop())
      }
    }
  }, [])

  return {
    stream
  }
}
Back
© 2022 BBF Powered byNext.js&Prisma&Tailwind.css