import { useWebSocket, RealtimeAudio } from "@outspeed/react";

export function WebsocketApp() {
  const { 
    connect,
    connectionStatus,
    getRemoteAudioTrack
  } = useWebSocket({
    config: {
      // Add your function URL.
      functionURL: "my-function-url",
      audio: { echoCancellation: true },
    },
  });

  return (
    <div>
      <span>Connection Status: {connectionStatus}</span>
      {connectionStatus === "new" && <button onClick={connect}>Connect</button>}
      <RealtimeAudio track={getRemoteAudioTrack()} />
    </div>
  );
}

We assume you have already deployed your backend. If not, please follow this tutorial to deploy your backend with outspeed-client.
import { useWebSocket, RealtimeAudio } from "@outspeed/react";

export function WebsocketApp() {
  const { 
    connect,
    connectionStatus,
    getRemoteAudioTrack
  } = useWebSocket({
    config: {
      // Add your function URL.
      functionURL: "my-function-url",
      audio: { echoCancellation: true },
    },
  });

  return (
    <div>
      <span>Connection Status: {connectionStatus}</span>
      {connectionStatus === "new" && <button onClick={connect}>Connect</button>}
      <RealtimeAudio track={getRemoteAudioTrack()} />
    </div>
  );
}

The code shown establishes a socket connection with the backend and streams local audio.

  • We import the necessary components from the @outspeed/react.
  • useWebSocket: This hook is used to manage WebSocket connections. To learn more about useWebSocket visit here.
  • Configuration: The useWebSocket hook is configured with a URL (functionURL) and options to enable audio with echo cancellation.
  • Audio Stream: The RealtimeAudio component is used to play the remote audio stream.

Resources