Live stream call audio in browser
# support
u
@Vapi Support Bot @User how to use call listenUrl in browser (react app) to listen to the live stream?
c
Hi udAIan, To listen to a live call stream in a React app using the
listenUrl
, you can create a WebSocket connection to receive and play the audio data. Here's a basic outline of how you can achieve this: 1. Establish WebSocket Connection:
Copy code
javascript
   const ws = new WebSocket(listenUrl);
   
   ws.onopen = () => console.log("WebSocket connection established");
   ws.onerror = (error) => console.error("WebSocket error:", error);
2. Set Up Audio Context:
Copy code
javascript
   const audioContext = new (window.AudioContext || window.webkitAudioContext)();
   const audioQueue = [];
   
   ws.onmessage = (event) => {
     if (typeof event.data === 'object') {
       event.data.arrayBuffer().then((buffer) => {
         audioQueue.push(buffer);
       });
     }
   };
3. Decode and Play Audio:
Copy code
javascript
   const playAudio = () => {
     if (audioQueue.length > 0) {
       const buffer = audioQueue.shift();
       
       audioContext.decodeAudioData(buffer, (decodedData) => {
         const source = audioContext.createBufferSource();
         source.buffer = decodedData;
         source.connect(audioContext.destination);
         source.start(0);
       });
     }
     requestAnimationFrame(playAudio);
   };
   
   audioContext.onstatechange = () => {
     if (audioContext.state === 'running') {
       playAudio();
     }
   };
This implementation ensures that the audio stream is continuously decoded and played as more data is received. Make sure to handle WebSocket connections properly, including closing the connection when the component unmounts to avoid memory leaks. You may also want to check browser compatibility for the Web Audio API. For more details, you can refer to this [Call Control and Listen Feature documentation](https://docs.vapi.ai/calls/call-features).
2 Views