How to access buffer of received audio when using ...
# ask-ai
w
How to access buffer of received audio when using livekit-node backend sdk?
t
Thanks for reaching out, Rohit. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to access the buffer of received audio using the LiveKit Node.js backend SDK, you can use the
AudioStream
class to subscribe to an audio track and grab individual
AudioFrame
objects that hold the raw audio data. Here’s a simple way to do it: 1. Subscribe to a track: Just listen for the
TrackSubscribed
event on your
Room
object. 2. Create an `AudioStream`: Wrap the subscribed audio track with
AudioStream
. This gives you a readable stream of
AudioFrame
objects. 3. Access frame data: Go through the
AudioStream
and pull out the audio data from each
AudioFrame
. The
data
field holds the raw PCM audio samples as a byte buffer. Each
AudioFrame
also includes handy info like
sampleRate
,
channels
,
timestamp
, and of course, the raw audio
data
. Here’s a quick example to get you started:
Copy code
import { Room, TrackKind } from '@livekit/rtc-node';
import { AudioStream } from '@livekit/rtc-node';

const room = new Room();
const audioBuffer = [];

room.on('trackSubscribed', (track) => {
  if (track.kind === TrackKind.KIND_AUDIO) {
    const audioStream = new AudioStream(track);

    // Collect audio frames
    audioStream.forEach((frame) => {
      audioBuffer.push(frame);

      // Example: Stop after collecting 5 seconds of audio
      if (frame.timestamp > 5_000_000) {
        audioStream.cancel();
        console.log('Collected 5 seconds of audio');
      }
    });
  }
});
Once you’ve got your buffered frames, you can take it further—maybe convert them to WAV or send them off to other services for transcription or analysis. If you have any questions or want to chat more about it, I’m here to help! Sources: packages/livekit-rtc/src/proto/audio_frame_pb.ts | Capturing the First Few Seconds of a Call for Processing