Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
1.5 kB
2
Indexable
import React, { useEffect, useRef } from 'react';
import { Canvas } from '@react-three/fiber';
import { useMediaStream } from 'use-media-stream';

const VideoStream = () => {
  const videoRef = useRef();
  const mediaSourceRef = useRef();

  useEffect(() => {
    const mediaSource = new MediaSource();
    mediaSourceRef.current = mediaSource;

    const handleSourceOpen = () => {
      const mediaSource = mediaSourceRef.current;
      const sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E"');

      const socket = new WebSocket('ws://example.com/video-stream'); // WebSocket server address

      socket.addEventListener('message', (event) => {
        sourceBuffer.appendBuffer(event.data);
      });

      sourceBuffer.addEventListener('error', (event) => {
        console.error('Error occurred while appending video: ', event);
      });

      videoRef.current.src = URL.createObjectURL(mediaSource);
    };

    mediaSource.addEventListener('sourceopen', handleSourceOpen);

    return () => {
      // Clean up resources
      const mediaSource = mediaSourceRef.current;
      mediaSource.removeEventListener('sourceopen', handleSourceOpen);
      mediaSource.endOfStream();
    };
  }, []);

  return (
    <div>
      <video ref={videoRef} width="640" height="480" controls></video>
      <Canvas>
        {/* Your 3D scene components go here */}
      </Canvas>
    </div>
  );
};

export default VideoStream;