I'm trying to use the node server sdk to stream au...
# ask-ai
r
I'm trying to use the node server sdk to stream audio in base64 encoded mulaw 8K format into a participant track so that an agent can transcribe and respond, but no audio seems to be going through. Currently I'm following the following process:
Copy code
// Create the room and connect to it
this._room = new Room()
await this._room.connect(process.env.LIVEKIT_URL!, callerTokenJWT, { autoSubscribe: true, dynacast: false })

// Create the source track
this._source = new AudioSource(8000, 1)
this._track = LocalAudioTrack.createAudioTrack('audio', this._source)
const options = new TrackPublishOptions()
options.source = TrackSource.SOURCE_MICROPHONE
await this._room.localParticipant!.publishTrack(this._track, options)

// ... further down in the data stream
for (const event from stream) {
  const base64mulaw8k = event.delta
  const ulawBuffer = base64DecodeAudioUlaw(base64mulaw8k)
  const pcm = ulawToPcm(ulawBuffer)
  const frame8k = new AudioFrame(pcm, 8000, 1, 1)
  await this._source.captureFrame(frame8k)
}
t
Thanks for reaching out, James. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you out! Could you please share a bit more about how you're implementing the
base64DecodeAudioUlaw
and
ulawToPcm
functions? It would be great to know if the decoded PCM data is in the correct format, like an
Int16Array
, which the
AudioFrame
constructor expects. Also, have you noticed any errors or logs popping up during this process? Understanding these details will really help us get to the bottom of this together. Sources: examples/publish-wav/index.ts
r
No errors have been popping up, and here are the method implementations for you:
Copy code
const base64DecodeAudioUlaw = (base64String: string): Buffer => {
    const binaryString = Buffer.from(base64String, 'base64').toString('binary')
    const bytes = Buffer.alloc(binaryString.length)
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i)
    }
    return bytes
}

const ulawToPcm = (ulawBuffer: Buffer): Int16Array => {
    const pcmArray = new Int16Array(ulawBuffer.length)
    for (let i = 0; i < ulawBuffer.length; i++) {
        pcmArray[i] = mulawToLinear(ulawBuffer[i])
    }
    return pcmArray
}

const mulawToLinear = (ulaw: number): number => {
    ulaw = ~ulaw // Invert bits

    const sign = ulaw & 0x80
    const segment = (ulaw >> 4) & 0x07
    const quantization = ulaw & 0x0f

    // Reconstruct the linear sample
    let sample = (quantization << 1) + 33 // Add bias
    sample <<= segment + 2 // Scale by segment
    sample -= 33 // Remove bias

    // Apply sign
    if (sign) {
        sample = -sample
    }

    // Clamp to 16-bit range
    return Math.max(-32768, Math.min(32767, sample))
}
t
It looks like you're doing a great job with decoding and converting the audio data! Just a couple of things to double-check to make sure everything flows smoothly: the PCM data you pass to the
AudioFrame
constructor should be in the signed 16-bit little-endian PCM format (
Int16Array
). Here are a few friendly reminders to verify: • Make sure the
Int16Array
returned by
ulawToPcm
is actually in little-endian byte order. If it’s not, a little tweak to the byte order might be needed. • Check that the sample rate (8 kHz) and the channel count (1) align perfectly with what you’re passing to the
AudioFrame
constructor. • Take another look at the
mulawToLinear
function to confirm it’s converting μ-law values to linear PCM values correctly, staying within the -32768 to 32767 range. If you’ve gone through these and things still aren’t quite right, please don’t hesitate to reach out. I’m here to help you troubleshoot further and get everything working just right! Sources: packages/livekit-rtc/src/audio_stream.ts | agents/src/tts/tts.ts | Track egress | LiveKit docs
r
Got it figured out and it was a 🤦 moment for me. Because I'm upscaling from 8K to 48K sample rate, I need to pool the audio frames as they come in and then send them off once they reach a large enough sample size.
e
Hey @rich-application-94483 do you have like sample code on how you did both the sending and receiving ?
t
I'm really happy to hear that you were able to resolve the issue! While I don’t have access to specific sample code from other users, I’d love to help guide you through how to structure both the sending and receiving processes for audio streaming in LiveKit. Here’s a general outline to get you started: Sending Audio
Copy code
// Create the room and connect
const room = new Room();
await room.connect(LIVEKIT_URL, token, { autoSubscribe: true });

// Create the audio source and track
const audioSource = new AudioSource(8000, 1); // 8KHz sample rate
const audioTrack = LocalAudioTrack.createAudioTrack('audio', audioSource);
await room.localParticipant.publishTrack(audioTrack);

// Pool audio frames and send them
const framePool = [];
const FRAME_SIZE = 80; // Example size for 10ms at 8KHz

for (const event of stream) {
  const base64mulaw8k = event.delta;
  const ulawBuffer = base64DecodeAudioUlaw(base64mulaw8k);
  const pcm = ulawToPcm(ulawBuffer);

  framePool.push(...pcm);

  if (framePool.length >= FRAME_SIZE) {
    const frameData = new Int16Array(framePool.splice(0, FRAME_SIZE));
    const audioFrame = new AudioFrame(frameData, 8000, 1, FRAME_SIZE);
    await audioSource.captureFrame(audioFrame);
  }
}
Receiving Audio When it comes to receiving audio, you’ll want to subscribe to remote tracks and handle the audio data in a way that fits your application. Setting up your app to properly manage the audio track will make a big difference. If you have any more questions or need a hand with any part of the implementation, please don’t hesitate to reach out. I’m here to help!