How to build a Mediasoup server
Feb 24, 2024 · 2 min read
To build a mediasoup server, follow these steps
- Detailed steps below
Create a device
- You need to fetch the
rtpCapabilitiesexposed by the Router - Then on the client side, call Device.load with the
router.rtpCapabilitiesyou just fetched
Create a transport to produce:
- First create a server-side transport important: router.createWebRtcTransport()
- Then on the client, create the device via
new Device()and loadrouterRtpCapabilitiesvianewDevice.load({ routerRtpCapabilities }) - Then create the client-side transport via: device.createSendTransport()
- On the client, you must subscribe to the connect and produce events
- Connect: when the event fires client-side, send the
dtlsParametersexposed bytransport.once("connect")on the client- Once the response is received, call callback() or errback()
- Produce: when the event fires client-side, send
kindandrtpParametersexposed bytransport.once("produce")on the client- Once the response is received, call
callback({ id: produceId })or errback()
- Once the response is received, call
- Connect: when the event fires client-side, send the
- On the client, you must subscribe to the connect and produce events
- To trigger these events, create a stream (audio or video -> getUserMedia or other) then call the
transport.producemethod
const videoTrack = stream.getTracks()[0];
transport.produce({ track: videoTrack });
Create a transport to consume:
- First create a server-side transport important: router.createWebRtcTransport()
- Then on the client, create the device via
new Device()and loadrouterRtpCapabilitiesvianewDevice.load({ routerRtpCapabilities }) - Then create the client-side transport via: device.createRecvTransport()
- On the client, you must subscribe to the connect event
- Connect: when the event fires client-side, send the
dtlsParametersexposed bytransport.once("connect")on the client
- Connect: when the event fires client-side, send the
- On the client, you must subscribe to the connect event
- To trigger this event and consume the transport emitting the stream, send
clientRtpCapabilitiesandproducerId - On the backend, check that the user can actually consume the stream via:
router.canConsume({
producerId,
rtpCapabilities: clientRtpCapabilities,
});
- Once this step is done, consume the
producerIdandclientRtpCapabilitieson the backend, then returnconsumer.idandconsumer.rtpParameters - On the frontend, use these two parameters returned from the backend to consume the stream client-side:
const consumer = await transport.consume({
id: consumerId, // consumer.id returned by the backend; consumer = the backend's
producerId,
rtpParameters, // consumer.rtpParameters returned by the backend; consumer = the backend's
kind: 'video',
});
- Finally, grab the track via
consumer.track(frontend side), which you can use like this:
const stream = new MediaStream([consumer.track]);
videoRef.current.srcObject = stream;