give me code for a two-way, real-time audio transl...
# ask-ai
n
give me code for a two-way, real-time audio translation session between two remote participants, A and B, where each participant only hears the translated audio of the other.
t
Thanks for reaching out, Darshak. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're asking for code that creates a two-way, real-time audio translation session where A only hears B's translated audio and B only hears A's translated audio. Below is a concise, runnable Python example using LiveKit Agents patterns described earlier. It uses two translator agents (one per direction), each subscribing only to one participant's mic, performing STT → translate → TTS, and publishing the synthesized audio only to the target participant. Notes: • Replace the plugin initializations (Deepgram/OpenAI/Cartesia) with your configured plugin instances and credentials. • Ensure participants publish their microphone tracks with distinct identity or names "A" and "B" (or adapt lookup logic). • This example uses the LiveKit Agents voice pipeline primitives shown earlier. Code (Python):
Copy code
import asyncio
from livekit import agents, rtc
from livekit.agents import JobContext, WorkerOptions, cli
from livekit.agents.voice import VoicePipelineAgent
from livekit.agents.llm import FunctionContext
# Replace these plugin imports with your configured plugin bindings
from livekit.plugins import deepgram, openai, cartesia

# Translator agent: subscribes to source_id, translates to target_lang, publishes to target_id
class DirectionalTranslator:
    def __init__(self, source_id: str, target_id: str, stt_lang: str, tts_voice: str):
        self.source_id = source_id
        self.target_id = target_id
        self.stt = deepgram.STT(language=stt_lang)
        self.tts = cartesia.TTS(voice=tts_voice)
        self.llm = openai.LLM(model="gpt-4")  # used for translation step
        self.fnc_ctx = FunctionContext()
        self.agent_session: VoicePipelineAgent | None = None

    async def start(self, ctx: JobContext):
        # Create a voice pipeline but disable auto subscription so we control subscriptions
        self.agent_session = VoicePipelineAgent(
            ctx.room,
            stt=self.stt,
            tts=self.tts,
            llm=self.llm,
            fnc_ctx=self.fnc_ctx,
            auto_subscribe=agents.AutoSubscribe.SUBSCRIBE_NONE,
        )

        # Wait for the source participant and subscribe only to their microphone track(s)
        src = await ctx.room.wait_for_participant(self.source_id)
        for pub in src.tracks.values():
            if pub.source == rtc.TrackSource.SOURCE_MICROPHONE:
                await pub.set_subscribed(True)

        await self.agent_session.start()

        # Override speak/publish behavior: synthesize and publish only to the target participant
        original_speak = self.agent_session.agent.speak

        async def speak_to_target(text: str):
            # synthesize audio buffer/track from text
            output = await self.agent_session.synthesize(text)
            tgt = await self.agent_session.room.wait_for_participant(self.target_id)
            # publish synthesized audio to the target participant only
            # create a local audio track on behalf of the room/server and publish to target
            await tgt.local_audio_track.publish(output.track)

        # replace speak with our targeted speak
        self.agent_session.agent.speak = speak_to_target

# Entrypoints to register two workers: A->B and B->A
async def entrypoint_a_to_b(ctx: JobContext):
    # A speaks English; B should hear Spanish
    translator = DirectionalTranslator(
        source_id="A",
        target_id="B",
        stt_lang="en",
        tts_voice="male-es-v1",
    )
    await translator.start(ctx)
    # keep running until job stops
    await asyncio.Event().wait()

async def entrypoint_b_to_a(ctx: JobContext):
    # B speaks Spanish; A should hear English
    translator = DirectionalTranslator(
        source_id="B",
        target_id="A",
        stt_lang="es",
        tts_voice="female-en-v1",
    )
    await translator.start(ctx)
    await asyncio.Event().wait()

if __name__ == "__main__":
    cli.register_worker(
        WorkerOptions(
            worker_type=agents.WorkerType.JOB,
            entrypoint_fnc=entrypoint_a_to_b,
            name="translator-a-to-b",
        )
    )
    cli.register_worker(
        WorkerOptions(
            worker_type=agents.WorkerType.JOB,
            entrypoint_fnc=entrypoint_b_to_a,
            name="translator-b-to-a",
        )
    )
    cli.run_app()
Key points to implement on your side: • STT: configure language models/recognizers for the source language. • Translation: use the LLM or translation API to convert recognized text to the target language before TTS. • TTS: select voices for clarity and latency trade-offs. • Subscriptions: ensure agents subscribe only to the source mic to prevent hearing original audio. • Publishing: publish synthesized audio as a local audio track visible only to the intended participant. If you'd like, I can: • Show the missing translation step inside the pipeline (STT → LLM translate → TTS) with code snippets, or • Adapt the example to use different plugin providers or to suppress direct peer audio on the client side. Which would you prefer? Sources: LiveKit Docs
n
in the same two remote participant
t
Do you mean you want both translation directions handled in a single agent/process (one program) running in the same LiveKit room for participants A and B, or do you mean both participants are on the same client/device and need local routing? Also please confirm: • Participant identities you use (are they "A" and "B"?). • Source and target languages for each direction (A→B, B→A). • Whether you prefer a single combined agent or two separate agents.
n
consider room where one is agent but don't want to create agent session and also there are two participant who joined the room
t
Thanks — I understand you want a single agent (already present in the room) to handle both A→B and B→A translation without creating separate agent sessions. Quick clarifying questions so I provide the right code: 1. Do participants identify as "A" and "B" (exact identity strings)? 2. Source/target languages for each direction (e.g., A speaks en → B hears es; B speaks es → A hears en)? 3. Do you want the agent to: ◦ transcribe → translate → synthesize and publish translated audio as separate local tracks for each target participant (server-side publish), or ◦ return translated audio to the clients to play locally? 1. Which STT/TTS/translation providers do you plan to use (Deepgram/OpenAI/Cartesia or others)? Once you confirm, I’ll provide a single-agent Python example that: • subscribes selectively to both participants' mic tracks, • runs STT → translate → TTS per direction, • publishes synthesized audio only to the intended recipient within the same room.
n
i don't know the remote participant id, but i know the language do it on participant track transcribe → translate → synthesize and publish STT/TTS/translation -> give me interface
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!