im using android sdk, how to send custom pcm audio...
# ask-ai
b
im using android sdk, how to send custom pcm audio data to the room (not from microphone)
t
Thanks for reaching out, Taras. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to send custom PCM audio (not microphone) into a LiveKit room using the Android SDK. You can do this by creating a programmatic audio source, making a LocalAudioTrack from it, and repeatedly pushing PCM frames into that source. Below are concise steps and a Kotlin example. 1) Choose PCM params • Format: signed 16-bit PCM (
pcm_s16le
) • Sample rate and channels must match sender and encoding (common: 48000 Hz, mono) • Frame length: typically 10ms or 20ms (at 48kHz, 10ms = 480 samples) 2) Create an AudioSource and LocalAudioTrack • Construct an AudioSource configured with your sample rate and channel count. • Create a
LocalAudioTrack
from that source and publish it via
localParticipant.publishAudioTrack(...)
. • Set
source = Track.Source.UNKNOWN
in publish options if you want metadata to reflect a non-microphone source. 3) Feed PCM frames continuously • Convert your PCM bytes into 16-bit samples (ShortArray). • Build audio frames matching the AudioSource API (sample rate, channels, sample count). • Call the AudioSource capture method (e.g.,
captureFrame(...)
) for each frame on a background thread/timer at real-time intervals. Minimal Kotlin-like pseudocode
Copy code
val sampleRate = 48000
val channels = 1
val frameMs = 10
val samplesPerFrame = (sampleRate * frameMs) / 1000

val audioSource = AudioSource(sampleRate, channels)
val localTrack = LocalAudioTrack.createAudioTrack("custom-audio", audioSource)

val publishOptions = TrackPublishOptions(source = Track.Source.UNKNOWN)
localParticipant.publishAudioTrack(localTrack, publishOptions)

val executor = Executors.newSingleThreadScheduledExecutor()
executor.scheduleAtFixedRate({
    // obtain `pcmBytes` from your generator/decoder; must be little-endian 16-bit PCM
    val shortSamples = ShortArray(samplesPerFrame)
    // fill shortSamples from pcmBytes
    val frame = AudioFrame.create(sampleRate, channels, samplesPerFrame)
    frame.setData(shortSamples)
    audioSource.captureFrame(frame)
}, 0, frameMs.toLong(), TimeUnit.MILLISECONDS)
Notes and tips • PCM must be 16-bit signed. Ensure correct endianness when converting bytes -> shorts. • Keep timing consistent (use a scheduled executor) to avoid underruns or jitter. • Run capture on a background thread; avoid UI thread blocking. • Match sample rate & channels to what you configure on the AudioSource. • If you need help mapping your specific PCM byte layout to ShortArray or with threading/timers, tell me the sample rate, channels, and whether your PCM is interleaved or planar and I’ll give a code snippet for conversion. Sources: Camera & microphone | LiveKit docs | Android quickstart | LiveKit docs | client-sdk-android | livekit/livekit_composite | DeepWiki
b
in logs i see that only microphone source is accepted. how can i change this ?
Copy code
"key": "accepted_sources",
"value": {
  "arrayValue": {
    "values": [
      {
        "stringValue": "SOURCE_MICROPHONE"
      }
    ]
  }
t
You're seeing that the participant token only allows
SOURCE_MICROPHONE
. That is controlled by the access token's publish sources (server-side), not the Android client. To allow your custom audio source: 1. Update the token generation on your backend to include the desired sources in
canPublishSources
of the Video/VideoGrant. Example (Node/Python-style): • Allow microphone and screen-share-audio:
Copy code
{
  "video": {
    "room": "my-room",
    "roomJoin": true,
    "canPublish": true,
    "canPublishSources": [
      "microphone",
      "screen_share_audio"
    ]
  }
}
1. When publishing the programmatic track from Android, set the track source to match a permitted source (e.g.,
SOURCE_MICROPHONE
or
SOURCE_SCREEN_SHARE_AUDIO
):
Copy code
val options = TrackPublishOptions(source = TrackSource.SOURCE_MICROPHONE)
localParticipant.publishTrack(localAudioTrack, options)
If you want to allow all sources, omit
canPublishSources
when creating the grant. Tell me: • do you control token generation on your backend, and • which source string you want to allow (e.g.,
microphone
,
screen_share_audio
)? I’ll give the exact code snippet for your backend language. Sources: Rooms, participants, and tracks | LiveKit docs | server-sdk-go | livekit/livekit_composite | DeepWiki | livekit/livekit_composite | DeepWiki | server-sdk-js | livekit/livekit_composite | DeepWiki
b
i want to allow SOURCE_UNKNOWN
t
You can allow
SOURCE_UNKNOWN
by adding it to the token's publish sources on your backend. Update the Video/VideoGrant
canPublishSources
array to include
"unknown"
(the grant uses lowercase source strings). Examples: Node (JS/TS)
Copy code
at.addGrant({
  room: 'my-room',
  roomJoin: true,
  canPublish: true,
  canPublishSources: ['microphone', 'screen_share_audio', 'unknown']
});
Python
Copy code
at.video_grant = VideoGrant(
  room='my-room',
  room_join=True,
  can_publish=True,
  can_publish_sources=['microphone', 'screen_share_audio', 'unknown']
)
Kotlin/Java backend (pseudo)
Copy code
videoGrant = VideoGrant(room = "my-room", roomJoin = true, canPublish = true,
                        canPublishSources = listOf("microphone","screen_share_audio","unknown"))
token.addGrant(videoGrant)
Client side: when publishing your programmatic track, set the track source to
SOURCE_UNKNOWN
(or
TrackSource.SOURCE_UNKNOWN
) so it matches the token grant. If you tell me which backend language you use, I’ll provide the exact snippet for your setup.
b
im using python sdk token is generated like this token = api.AccessToken(api_key=lk_api_key, api_secret=lk_api_secret) \ .with_identity(identity) \ .with_name(identity) \ .with_grants(api.VideoGrants( room_join=True, room=room, )).to_jwt()
t
You're already generating the token in Python — add
can_publish_sources=['unknown']
to the VideoGrant. That will allow
SOURCE_UNKNOWN
for programmatic tracks. Example:
Copy code
from livekit import api

token = (
  api.AccessToken(api_key=lk_api_key, api_secret=lk_api_secret)
    .with_identity(identity)
    .with_name(identity)
    .with_grants(
      api.VideoGrants(
        room_join=True,
        room=room,
        can_publish=True,
        can_publish_sources=['unknown'],  # allow SOURCE_UNKNOWN
      )
    )
    .to_jwt()
)
On the Android client, publish your custom track with
TrackSource.SOURCE_UNKNOWN
so it matches the grant:
Copy code
options.source = TrackSource.SOURCE_UNKNOWN
localParticipant.publishTrack(localAudioTrack, options)
Would you like the exact import path or snippet adjusted for your LiveKit Python package version?
b
how to allow any source ?
t
To allow any source, omit
can_publish_sources
when creating the VideoGrant (no need to list sources). Example in Python using your existing code:
Copy code
from livekit import api

token = (
  api.AccessToken(api_key=lk_api_key, api_secret=lk_api_secret)
    .with_identity(identity)
    .with_name(identity)
    .with_grants(
      api.VideoGrants(
        room_join=True,
        room=room,
        can_publish=True,   # allow publishing
        # no can_publish_sources -> all sources allowed
      )
    )
    .to_jwt()
)
Client: publish your track with the appropriate
TrackSource
(or
SOURCE_UNKNOWN
) — any source will be accepted since the token doesn't restrict sources.
b
still accepted_sources: [0: "SOURCE_MICROPHONE" ] after can_publish=True, # allow publishing can_publish_sources=['microphone', 'screen_share_audio', 'unknown'] )
t
Thanks — I understand you still see
SOURCE_MICROPHONE
in
accepted_sources
after adding sources to the grant. That value is driven by the token the server accepts for the participant. Let's check a few things to find the mismatch. Please confirm these three items: 1. Are you regenerating and using the new JWT after changing the VideoGrant? (Old tokens still enforce previous restrictions.) 2. Where is the token generated and delivered from (your backend process or a separate service)? Make sure the environment that generates tokens is the one you edited. 3. Can you paste the exact VideoGrant payload you send (redact keys/secrets)? e.g. { "room": "my-room", "roomJoin": true, "canPublish": true, "canPublishSources": [...] } If you prefer a quick checklist to try now: • Regenerate the token with either: ◦ no
can_publish_sources
(allows any source), or ◦
can_publish_sources: ["microphone","screen_share_audio","unknown"]
• Restart whatever process serves tokens so it uses the updated code/env • Confirm the client receives the new JWT (log the token creation time or payload on the backend and the token used on the client) • On Android, publish with
TrackSource.SOURCE_UNKNOWN
(or matching source string) Share your answers or the grant payload and I’ll tell you exactly what to change next.
b
how to fix this eror audio output is enabled but RealtimeModel has no audio modality and no TTS is set. Either enable audio modality in the RealtimeModel or set a TTS model.
t
You're seeing the error because your session expects audio output but the model isn't configured to produce audio and no TTS is provided. Fix it by doing one of the two options below. Option A — enable audio modality in the RealtimeModel (model will produce audio directly) • Ensure the model's
modalities
includes
"AUDIO"
. • Example (Python):
Copy code
from livekit.plugins import google
from livekit.agents import AgentSession

session = AgentSession(
    llm=google.realtime.RealtimeModel(
        model="your-audio-capable-model",
        modalities=["AUDIO"],
    ),
)
Option B — keep the model text-only and provide a TTS model (convert text → speech) • Use
modalities=["TEXT"]
(or omit AUDIO) and set
tts
to a supported TTS model. • Example (Python):
Copy code
from livekit.plugins import google
from livekit.agents import AgentSession

session = AgentSession(
    llm=google.realtime.RealtimeModel(modalities=["TEXT"]),
    tts="cartesia/sonic-3",  # or another supported TTS provider
)
Quick checklist • If you want direct audio responses → use Option A and pick an audio-capable realtime model. • If you want text responses converted to speech → use Option B and set a
tts
model. • Restart/recreate the AgentSession after changing config. Tell me which provider/model you're using (OpenAI/Gemini/other) and whether you prefer model-generated audio or separate TTS, and I’ll give the exact snippet for your setup. Sources: Agent session | LiveKit docs | Gemini Live API plugin | LiveKit docs | OpenAI Realtime API plugin guide | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Text-to-speech (TTS) models | LiveKit Docs
b
i have memory leaks in android, what can cause it in live kit sdk ?
t
You're asking what in the LiveKit Android SDK can cause memory leaks. Common causes and what to check/fix: 1. Not disconnecting the Room • Call
room.disconnect()
when leaving the screen (e.g., in
onDestroy()
). • A connected Room holds listeners, participants, and native WebRTC resources. 1. Unreleased video renderers • If you call
videoTrack.addRenderer(renderer)
, call
videoTrack.removeRenderer(renderer)
before destroying the view. • Release
SurfaceViewRenderer
/
GLSurfaceView
resources in the view lifecycle. 1. Uncancelled event collectors / listeners • Cancel coroutine collectors (e.g., Flow
collect
) or remove listeners when the Activity/Fragment is destroyed. • Use lifecycle-aware scopes or explicitly cancel jobs in
onDestroy()
. 1. Published tracks not stopped/unpublished • Stop camera/microphone and unpublish tracks:
localParticipant.unpublishTrack(track)
or disable and release capture resources. • Ensure any custom `AudioSource`/`VideoSource` you created is stopped and released. 1. Foreground service or background tasks left running • If using foreground services for background audio/video, call
stopForeground(true)
and
stopSelf()
when done. • Ensure scheduled executors/threads feeding programmatic sources are shut down. 1. Data channel / callback closures capturing Context • Avoid lambdas or callbacks that capture Activity/Fragment references; use weak refs or clear handlers on teardown. 1. Native WebRTC objects retained • Ensure SDK cleanup paths complete so native peers and tracks are freed. Check for leaked native WebRTC types in the Memory Profiler. Troubleshooting steps • Use Android Studio Memory Profiler after leaving the room. Look for retained instances of
Room
,
LocalParticipant
,
SurfaceViewRenderer
,
VideoTrack
, or your Activity. • Capture a heap dump and examine GC roots to find what's holding references. • Add logging in your cleanup code to confirm
disconnect()
,
removeRenderer()
,
unpublishTrack()
and coroutine cancellations are called. Quick checklist to add to your teardown • Stop and release any custom capture sources (audio/video). • Unpublish published tracks. • Remove renderers from tracks and release view renderers. • Cancel coroutine jobs / Flow collectors. • Call
room.disconnect()
and null out references. • Shutdown executors/threads and stop foreground service if used. If you share a short snippet of your connection/teardown code (how you create/publish tracks, where you call
disconnect()
and how you handle renderers/listeners), I can point out exact changes to prevent leaks. Sources: client-sdk-android | livekit/livekit_composite | DeepWiki | Connecting to LiveKit | LiveKit docs | Handling events | LiveKit docs | Android quickstart | LiveKit docs
b
its happend just after connecting to the room
t
Thanks — since the leak happens immediately after connecting, that narrows likely causes. Check these items and share your connection code if you want pinpointed fixes. 1) Confirm you're disconnecting previous Room instances • Ensure you don't create a new Room without calling
previousRoom.disconnect()
and nulling references. Multiple active Room objects immediately hold resources. 2) Track creation/publishing at connect time • If you create/publish LocalAudioTrack or LocalVideoTrack right after connect, ensure you later unpublish and release them. Verify you aren't repeatedly creating tracks on reconnects. 3) Renderers added on participantSubscribed events • If you add a renderer (e.g.,
videoTrack.addRenderer(surface)
) when subscribing, remove it on unsubscribe and when Activity/Fragment is destroyed. Adding without removing on every connect will leak. 4) Un-cancelled event collectors/listeners started at connect • Check any
room.events.collect { ... }
, listeners, or callbacks launched when connected. If you start collectors in a scope that survives the Activity (or don't cancel), they retain the Activity/context. Use lifecycleScope tied to view lifecycle or cancel jobs in teardown. 5) Background threads/executors started on connect • If you start executors for custom audio/video capture or polling, ensure they are stopped and shutdown on disconnect. Threads left alive will retain references. 6) Foreground service or media sessions started on connect • If you start a service for background audio/video on connect, ensure it's stopped when not needed. 7) Native leaks visible right after connect • Use Memory Profiler immediately after connect to see which objects increase: Room, LocalParticipant, SurfaceViewRenderer, VideoTrack, or custom classes. Heap dump and GC roots will show what holds them. Quick debug steps to run now • Connect, then immediately call
room.disconnect()
and run GC; if memory drops, something in your connected lifecycle isn't cleaned up. • Add logging to your connect path to ensure you only create one Room and one set of tracks/renderers. • Take a heap snapshot after connect and inspect retained instances and their GC roots. If you paste your connect/subscribe and teardown code (how you create Room, publish tracks, add renderers, and where you call disconnect), I’ll point out exact lines to change.