I want audio track subscribe bi-direction from liv...
# ask-ai
a
I want audio track subscribe bi-direction from livekit room only participate and i will connect websocket and will do bi-direction audio transfer on that websocket. can we do with go language?
t
Thanks for reaching out, Parth. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking if you can implement bi-directional audio in a LiveKit room using Go and a WebSocket for the audio transfer. Yes — you can. Below is a concise plan and the key steps you can follow. What you can do • Join the room with the LiveKit Go SDK as a participant. • Subscribe to remote audio tracks (receive PCM frames). • Send those frames over your WebSocket to your external service. • Receive audio frames back on the WebSocket and publish them as a local audio track into the room. High-level steps (Go) 1. Join room and handle published tracks ◦ Use the Go SDK room callbacks: OnTrackPublished / OnTrackSubscribed. ◦ For audio publications call
publication.SetSubscribed(true)
(or rely on autoSubscribe). 1. Read raw audio frames from remote audio tracks ◦ In OnTrackSubscribed, get the
RemoteAudioTrack.AudioStream()
and read frames from its channel. ◦ Forward frame data (PCM
s16
bytes) over your WebSocket connection. 1. Publish audio received from WebSocket ◦ Create a
LocalAudioTrack
backed by an
AudioSource
(e.g.,
rtc.NewAudioSource(...)
). ◦ Push incoming PCM frames from your WebSocket into
AudioSource.CaptureFrame(...)
. ◦ Publish the local track via
LocalParticipant.PublishTrack(...)
. 1. WebSocket handling ◦ Use a Go WebSocket client/server (e.g., gorilla/websocket). ◦ Exchange raw PCM binary frames (agree on sample rate, channels, format — typically pcm_s16le). ◦ Keep audio buffering/latency and resampling in mind if sample rates differ. Alternatives / useful features • Use LiveKit Track Egress to stream an individual track to a WebSocket if you prefer server-side egress rather than reading tracks via a participant. • If you need lower-level control or third‑party processing, using a dedicated audio pipeline (resampler, jitter buffer) between LiveKit frames and your WebSocket is recommended. If you want, I can: • Show a short Go code snippet for subscribing and reading
AudioStream
frames. • Show a short Go snippet for creating a
LocalAudioTrack
and pushing PCM frames into it. Which snippet would help you first? Sources: Live Conversations with AI using ChatGPT and WebRTC | Track egress | LiveKit docs
a
write a sample code please
t
Thanks — I’ll provide a corrected, self‑contained Go example that: • uses the LiveKit client SDK to join a room as a participant, • subscribes to remote audio and reads PCM frames from
RemoteAudioTrack.AudioStream()
, • forwards PCM frames to an external WebSocket, • reads PCM frames from the WebSocket and publishes them back using a
LocalAudioTrack
backed by an
AudioSource
, • includes notes where encoding/resampling may be required. One quick question before I generate the code: do you want the example to assume the WebSocket sends/receives raw PCM signed 16-bit little-endian (pcm_s16le) at 48 kHz mono? If yes, I’ll produce the code using that format. If your external service uses a different format (e.g., 16 kHz, stereo, or Opus), tell me which so I can include resampling/encoding steps. Sources: Live Conversations with AI using ChatGPT and WebRTC
a
client is like AI Agent and other person also join like SIP/web call
t
Thanks — I’ll give a focused Go sample that fits your scenario: an AI agent joins a LiveKit room, subscribes to a participant’s audio (e.g., SIP/web call), forwards raw PCM to an external AI service over WebSocket, receives processed PCM back, and publishes that audio into the room. Assumptions (confirm or change if needed) • WebSocket payloads are raw PCM signed 16-bit little-endian (pcm_s16le). • Sample rate: 48 kHz, mono. • LiveKit Go client exposes
RemoteAudioTrack.AudioStream()
to read frames and an `AudioSource`/`LocalAudioTrack` to publish (the sample uses typical SDK patterns). • You will supply LIVEKIT_URL, API key/secret, room name, and agent identity via environment variables. Core points shown in the sample • Join room as a participant. • Subscribe and read PCM frames from remote audio tracks. • Send PCM frames to WebSocket and concurrently read processed PCM frames from WebSocket. • Push incoming PCM into a local audio source and publish it. Sample code (concise, illustrative)
Copy code
package main

import (
	"context"
	"encoding/binary"
	"log"
	"os"
	"os/signal"
	"time"

	"github.com/gorilla/websocket"
	lksdk "github.com/livekit/server-sdk-go"     // room SDK types
	"github.com/livekit/protocol/auth"
	"github.com/pion/webrtc/v3"
)

// NOTE: Replace imports above with exact packages you use from LiveKit Go SDK.
// This example is illustrative and may need small changes to match SDK versions.

func main() {
	apiKey := os.Getenv("LIVEKIT_API_KEY")
	apiSecret := os.Getenv("LIVEKIT_API_SECRET")
	livekitURL := os.Getenv("LIVEKIT_URL") // e.g. wss://livekit.example.com
	roomName := os.Getenv("LIVEKIT_ROOM")
	identity := os.Getenv("LIVEKIT_IDENTITY") // e.g. "ai-agent"

	if apiKey == "" || apiSecret == "" || livekitURL == "" || roomName == "" || identity == "" {
		log.Fatal("Please set LIVEKIT_API_KEY, LIVEKIT_API_SECRET, LIVEKIT_URL, LIVEKIT_ROOM, LIVEKIT_IDENTITY")
	}

	// Create token
	at := auth.NewAccessToken(apiKey, apiSecret)
	vg := &auth.VideoGrant{RoomJoin: true, Room: roomName}
	at.AddGrant(vg).SetIdentity(identity).SetValidFor(24 * time.Hour)
	token, err := at.ToJWT()
	if err != nil {
		log.Fatalf("token: %v", err)
	}

	// Connect to room (use the LiveKit Go client to join as participant).
	// Replace this with the actual connect call for your SDK version.
	room, err := lksdk.ConnectToRoom(context.Background(), livekitURL, token, &lksdk.RoomConfig{
		Name: roomName,
	})
	if err != nil {
		log.Fatalf("connect room: %v", err)
	}
	defer room.Disconnect()
	log.Println("joined room:", roomName)

	// Create and publish a local audio track that we'll feed with incoming WebSocket audio
	audioSource := NewMemoryAudioSource(48000, 1) // sampleRate=48000, channels=1
	localTrack, err := audioSource.LocalTrack()
	if err != nil {
		log.Fatalf("creating local track: %v", err)
	}
	if _, _, err = room.LocalParticipant.PublishTrack(localTrack, &lksdk.TrackPublicationOptions{Name: "ai-out"}); err != nil {
		log.Fatalf("publish local track: %v", err)
	}
	log.Println("published local track: ai-out")

	// Dial WebSocket to AI service
	wsURL := os.Getenv("WS_URL") // e.g. wss://ai-service.example.com/stream
	wsConn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
	if err != nil {
		log.Fatalf("websocket dial: %v", err)
	}
	defer wsConn.Close()
	log.Println("connected to websocket:", wsURL)

	// Handle remote audio tracks
	room.OnTrackSubscribed(func(track *lksdk.RemoteAudioTrack, pub *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) {
		log.Printf("subscribed to audio from %s\n", rp.Identity())

		stream := track.AudioStream()
		go func() {
			for {
				select {
				case <-room.Context().Done():
					return
				case frame, ok := <-stream.Channel():
					if !ok {
						log.Println("audio stream closed")
						return
					}
					// frame.Data() is PCM bytes (assumed pcm_s16le)
					if err := wsConn.WriteMessage(websocket.BinaryMessage, frame.Data()); err != nil {
						log.Printf("ws write: %v", err)
						return
					}
				}
			}
		}()
	})

	// Read from WebSocket and push into local audio source
	go func() {
		for {
			msgType, msg, err := wsConn.ReadMessage()
			if err != nil {
				log.Printf("ws read error: %v", err)
				return
			}
			if msgType != websocket.BinaryMessage {
				continue
			}
			// msg contains PCM s16le bytes in our assumption.
			// Push into audio source in frames expected by SDK.
			if err := audioSource.PushPCM(msg); err != nil {
				log.Printf("audioSource push: %v", err)
				return
			}
		}
	}()

	// Simple ping to keep WebSocket alive (optional)
	go func() {
		t := time.NewTicker(5 * time.Second)
		defer t.Stop()
		for range t.C {
			_ = wsConn.WriteMessage(websocket.PingMessage, nil)
		}
	}()

	// Wait for interrupt
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt)
	<-stop
	log.Println("shutting down")
}
Helper/placeholder API (you must implement or adapt these to your SDK): • NewMemoryAudioSource(sampleRate int, channels int) returns an object that: ◦ provides
LocalTrack() (*lksdk.LocalAudioTrack, error)
to publish, ◦ provides
PushPCM([]byte) error
to feed raw PCM frames (pcm_s16le) into the track, ◦ internally handles framing expected by LiveKit (samples per frame), buffering, and any necessary conversion. Implementation notes • LiveKit remote audio track frames can be accessed through
RemoteAudioTrack.AudioStream()
which yields frames containing PCM bytes. • Ensure the WebSocket and LiveKit agree on sample rate and channel count. If your SIP/web caller uses a different sample rate, insert resampling before publishing. • If your AI service expects or returns encoded audio (e.g., Opus), you must encode/decode accordingly. • Add jitter buffering and small packet timestamps to avoid audio glitches. • For production, add reconnection, error handling, and resource cleanup. If you’d like, I can: • Provide a concrete implementation of
MemoryAudioSource
that uses the LiveKit Go SDK primitives (showing how to create an
AudioSource
and call `CaptureFrame`/`Push`), or • Adapt the example for a different sample rate / stereo / or Opus transport. Which helper would you like next?
a
24KHz pipleline i have
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!