### Install LiveKit Go SDK Source: https://github.com/livekit/server-sdk-go/blob/main/README.md Install the LiveKit Go SDK v2 using the go get command. Requires Go 1.18+. ```shell go get github.com/livekit/server-sdk-go/v2 ``` -------------------------------- ### Example: Implement PCMRemoteTrackWriter and Create Track Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/07-media-apis.md Demonstrates how to implement the PCMRemoteTrackWriter interface and use it to create a PCM remote track. This example shows basic processing of PCM16 samples and setting a target sample rate. ```go import ( "github.com/livekit/media-sdk" lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" ) type MyAudioWriter struct {} func (w *MyAudioWriter) WriteSample(sample media.PCM16Sample) error { // Process PCM16 sample return nil } func (w *MyAudioWriter) Close() error { return nil } // In track subscription callback writer := &MyAudioWriter{} pcmTrack, err := lkmedia.NewPCMRemoteTrack( remoteTrack, writer, lkmedia.WithTargetSampleRate(16000), lkmedia.WithTargetChannels(1), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Go Data Messaging Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md Demonstrates sending and receiving data packets within a LiveKit room. Includes examples for broadcasting to all participants and sending private messages to specific users. Ensure the SDK is imported and a room connection is established. ```go package main import ( "context" "fmt" "log" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { callback := &lksdk.RoomCallback{ ParticipantCallback: lksdk.ParticipantCallback{ OnDataPacket: func( data lksdk.DataPacket, params lksdk.DataReceiveParams, ) { fmt.Printf("Data from %s: %v\n", params.ParticipantName, data) if userData, ok := data.(*lksdk.UserDataPacket); ok { fmt.Printf("Payload: %s\n", string(userData.Payload)) } }, }, } room, _ := lksdk.ConnectToRoom( "https://livekit.example.com", lksdk.ConnectInfo{ APIKey: "key", APISecret: "secret", RoomName: "room", ParticipantIdentity: "user", }, callback, ) defer room.Disconnect() // Send data to all participants ctx := context.Background() err := room.LocalParticipant.PublishData( ctx, []byte("Hello everyone!"), lksdk.WithDataPublishTopic("chat"), lksdk.WithDataPublishReliable(true), ) if err != nil { log.Printf("Error publishing data: %v", err) } // Send data to specific participants err = room.LocalParticipant.PublishData( ctx, []byte("Private message"), lksdk.WithDataPublishDestination([]string{"user-456"}), ) if err != nil { log.Printf("Error publishing data: %v", err) } select {} } ``` -------------------------------- ### StartRoomCompositeEgress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording a room composite, capturing media from all participants in the room. ```APIDOC ## StartRoomCompositeEgress ### Description Starts recording a room composite (all participants). ### Signature ```go func (c *EgressClient) StartRoomCompositeEgress( ctx context.Context, req *livekit.RoomCompositeEgressRequest, ) (*livekit.EgressInfo, error) ``` ### Returns `*livekit.EgressInfo` - egress session info. ``` -------------------------------- ### Egress (Recording) Management in LiveKit Go SDK Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md This snippet demonstrates how to start, list, and stop egress (recording) sessions for a LiveKit room. It shows starting a room composite recording to an S3 bucket and retrieving its status. Ensure you have valid S3 credentials and bucket configuration. ```go package main import ( "context" "fmt" "log" "github.com/livekit/protocol/livekit" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { ctx := context.Background() egressClient := lksdk.NewEgressClient( "https://livekit.example.com", "api-key", "api-secret", ) // Start room composite recording (all participants) egress, err := egressClient.StartRoomCompositeEgress(ctx, &livekit.RoomCompositeEgressRequest{ RoomName: "my-room", Layout: "speaker-light", Output: &livekit.RoomCompositeEgressRequest_File{ File: &livekit.FileOutput{ FileType: livekit.FileType_MP4, Filepath: "s3://bucket/recording.mp4", }, }, }) if err != nil { log.Fatal(err) } fmt.Printf("Started egress: %s\n", egress.EgressId) // Get status fmt.Printf("Status: %v\n", egress.State) // List all active egress sessions list, err := egressClient.ListEgress(ctx, &livekit.ListEgressRequest{ RoomName: "my-room", }) if err != nil { log.Fatal(err) } fmt.Printf("Active egress sessions: %d\n", len(list.Items)) // Stop egress _, err = egressClient.StopEgress(ctx, &livekit.StopEgressRequest{ EgressId: egress.EgressId, }) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Implement CustomAudioProvider Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/07-media-apis.md Example implementation of a custom audio provider. Use this with a local track to stream custom audio data. ```go type CustomAudioProvider struct { // ... source state } func (p *CustomAudioProvider) NextSample(ctx context.Context) (media.Sample, error) { // Generate or read next audio sample return sample, nil } // Use with local track track := lksdk.NewLocalTrackWithProvider( webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus}, myProvider, ) ``` -------------------------------- ### Start Participant Egress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording the media of a single participant within a room. Returns egress session information. ```go func (c *EgressClient) StartParticipantEgress( ctx context.Context, req *livekit.ParticipantEgressRequest, ) (*livekit.EgressInfo, error) ``` -------------------------------- ### StartParticipantEgress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording the media of a single participant within a room. ```APIDOC ## StartParticipantEgress ### Description Starts recording a single participant's media. ### Signature ```go func (c *EgressClient) StartParticipantEgress( ctx context.Context, req *livekit.ParticipantEgressRequest, ) (*livekit.EgressInfo, error) ``` ``` -------------------------------- ### ParticipantKind Usage Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Example of setting the ParticipantKind in ConnectInfo. ```go info := lksdk.ConnectInfo{ ParticipantKind: lksdk.ParticipantAgent, // ... } ``` -------------------------------- ### Receive and Process Audio Tracks in Go Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md This example demonstrates how to subscribe to audio tracks, decode Opus to PCM, and process the audio samples. It requires setting up a callback for track subscriptions and a custom writer to handle audio data. ```go package main import ( "fmt" "log" "github.com/pion/webrtc/v4" lksdk "github.com/livekit/server-sdk-go/v2" lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" ) type AudioWriter struct { sampleCount int } func (w *AudioWriter) WriteSample(sample media.PCM16Sample) error { w.sampleCount++ if w.sampleCount%240 == 0 { fmt.Printf("Received %d audio samples\n", w.sampleCount) } return nil } func (w *AudioWriter) Close() error { fmt.Printf("Audio stream closed after %d samples\n", w.sampleCount) return nil } func main() { callback := &lksdk.RoomCallback{ ParticipantCallback: lksdk.ParticipantCallback{ OnTrackSubscribed: func( track *webrtc.TrackRemote, pub *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant, ) { fmt.Printf("Subscribed to %s from %s\n", pub.Name(), rp.Name()) if pub.Kind() == lksdk.TrackKindAudio { // Decode Opus to PCM writer := &AudioWriter{} pcmTrack, err := lkmedia.NewPCMRemoteTrack( track, writer, lkmedia.WithTargetSampleRate(16000), lkmedia.WithTargetChannels(1), ) if err != nil { log.Printf("Error creating PCM track: %v", err) return } go func() { // PCMRemoteTrack reads and decodes in background _ = pcmTrack }() } }, OnTrackUnsubscribed: func( track *webrtc.TrackRemote, pub *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant, ) { fmt.Printf("Unsubscribed from %s\n", pub.Name()) }, }, } room, _ := lksdk.ConnectToRoom( "https://livekit.example.com", lksdk.ConnectInfo{ APIKey: "key", APISecret: "secret", RoomName: "room", ParticipantIdentity: "user", }, callback, ) defer room.Disconnect() select {} } ``` -------------------------------- ### Publish Data Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Send binary data to other participants in the room, with options for topic and reliability. Requires a context for cancellation. ```go err := room.LocalParticipant.PublishData( ctx, []byte("Hello, room!"), lksdk.WithDataPublishTopic("chat"), lksdk.WithDataPublishReliable(true), ) if err != nil { log.Printf("Error publishing data: %v", err) } ``` -------------------------------- ### StartTrackCompositeEgress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording a composite stream of multiple selected tracks. ```APIDOC ## StartTrackCompositeEgress ### Description Starts recording a composite of multiple tracks. ### Signature ```go func (c *EgressClient) StartTrackCompositeEgress( ctx context.Context, req *livekit.TrackCompositeEgressRequest, ) (*livekit.EgressInfo, error) ``` ``` -------------------------------- ### Start Track Egress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording a single specified track. Returns egress session information. ```go func (c *EgressClient) StartTrackEgress( ctx context.Context, req *livekit.TrackEgressRequest, ) (*livekit.EgressInfo, error) ``` -------------------------------- ### LocalParticipant TrackPublications Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Iterate through and display information about all tracks published by the local participant. ```go tracks := room.LocalParticipant.TrackPublications() for _, track := range tracks { fmt.Printf("Published track: %s (muted: %v)\n", track.Name(), track.IsMuted()) } ``` -------------------------------- ### StartWebEgress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording the content of a specified web page. ```APIDOC ## StartWebEgress ### Description Starts recording from a web page. ### Signature ```go func (c *EgressClient) StartWebEgress( ctx context.Context, req *livekit.WebEgressRequest, ) (*livekit.EgressInfo, error) ``` ``` -------------------------------- ### Start Web Egress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initiates recording from a specified web page. Returns egress session information. ```go func (c *EgressClient) StartWebEgress( ctx context.Context, req *livekit.WebEgressRequest, ) (*livekit.EgressInfo, error) ``` -------------------------------- ### Publish PCM Audio Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md This example shows how to publish raw PCM audio data to a LiveKit room. It demonstrates creating a PCM track with specific audio parameters and writing samples, including silence. ```go package main import ( "context" "fmt" "log" lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" "github.com/livekit/protocol/logger" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { room, _ := connectToRoom() defer room.Disconnect() // Create PCM local track // 48kHz mono Opus audio track, err := lkmedia.NewPCMLocalTrack( 48000, // sample rate 1, // channels logger.GetLogger(), ) if err != nil { log.Fatal(err) } // Publish pub, err := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "microphone", }) if err != nil { log.Fatal(err) } fmt.Printf("Published PCM track: %s\n", pub.SID()) // Write PCM16 samples go func() { // Example: write 1-second silence sampleCount := 48000 // 48kHz * 1 second samples := make([]int16, sampleCount) sample := media.PCM16Sample{ Data: samples, Samples: sampleCount, PacketDuration: time.Millisecond * 20, } for i := 0; i < 50; i++ { // 50 * 20ms = 1 second if err := track.WriteSample(sample); err != nil { log.Printf("Error writing sample: %v", err) break } } track.Close() }() select {} } ``` -------------------------------- ### StartTrackEgress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Starts recording a single, specific track. ```APIDOC ## StartTrackEgress ### Description Starts recording a single track. ### Signature ```go func (c *EgressClient) StartTrackEgress( ctx context.Context, req *livekit.TrackEgressRequest, ) (*livekit.EgressInfo, error) ``` ``` -------------------------------- ### Publish Local Track Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Publish a new local WebRTC track to the room with specified publication options. Ensure the track is created before publishing. ```go track, _ := lksdk.NewLocalTrack( webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, ) pub, err := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "video", VideoWidth: 1920, VideoHeight: 1080, }) if err != nil { log.Fatal(err) } fmt.Printf("Track published: %s\n", pub.SID()) ``` -------------------------------- ### LocalParticipant Identity Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Retrieve the identity string of the local participant in a room. ```go identity := room.LocalParticipant.Identity() ``` -------------------------------- ### Publish a Video Track to a Room Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md Shows how to create and publish a new local video track (VP8) to an existing LiveKit room. This example assumes a room connection is already established. You will need to implement the logic to write video frames to the track. ```go package main import ( "fmt" "log" "time" "github.com/pion/webrtc/v4" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { room, _ := connectToRoom() defer room.Disconnect() // Create VP8 video track track, err := lksdk.NewLocalTrack( webrtc.RTPCodecCapability{ MimeType: webrtc.MimeTypeVP8, ClockRate: 90000, }, ) if err != nil { log.Fatal(err) } // Publish track pub, err := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "camera", Source: livekit.TrackSource_CAMERA, VideoWidth: 1920, VideoHeight: 1080, }) if err != nil { log.Fatal(err) } fmt.Printf("Published track: %s (SID: %s)\n", pub.Name(), pub.SID()) // TODO: Write video frames to track via track.WriteSample() } func connectToRoom() (*lksdk.Room, error) { return lksdk.ConnectToRoom( "https://livekit.example.com", lksdk.ConnectInfo{ APIKey: "key", APISecret: "secret", RoomName: "room", ParticipantIdentity: "user", }, nil, ) } ``` -------------------------------- ### Start Room Composite Egress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initiates a recording of a room's composite media, capturing all participants. Returns egress session information. ```go func (c *EgressClient) StartRoomCompositeEgress( ctx context.Context, req *livekit.RoomCompositeEgressRequest, ) (*livekit.EgressInfo, error) ``` -------------------------------- ### Start Track Composite Egress Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Begins recording a composite of multiple selected tracks. Returns egress session information. ```go func (c *EgressClient) StartTrackCompositeEgress( ctx context.Context, req *livekit.TrackCompositeEgressRequest, ) (*livekit.EgressInfo, error) ``` -------------------------------- ### Handle ErrInvalidParameter Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Example of how to check for and handle the ErrInvalidParameter error when creating a SIP inbound trunk. ```go _, err := sipClient.CreateSIPInboundTrunk(ctx, nil) if err == lksdk.ErrInvalidParameter { fmt.Println("Invalid trunk configuration") } ``` -------------------------------- ### Handle ErrNoPeerConnection Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Example of how to check for and handle the ErrNoPeerConnection error when publishing a track before the room connection is established. ```go pub, err := room.LocalParticipant.PublishTrack(track, opts) if err == lksdk.ErrNoPeerConnection { fmt.Println("Not connected to room yet") } ``` -------------------------------- ### Publish Video Track Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/README.md Publish a new local video track to the room. This example shows publishing a VP8 encoded track with specified video dimensions. ```go track, _ := lksdk.NewLocalTrack( webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8}, ) pub, _ := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "camera", VideoWidth: 1920, VideoHeight: 1080, }) ``` -------------------------------- ### Handle Context Deadline Exceeded Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Example demonstrating how to handle context cancellation errors, specifically context.DeadlineExceeded, for RPC calls. ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) deferr cancel() response, err := room.LocalParticipant.RPC(ctx, "method", "{}", "target-id") if err == context.DeadlineExceeded { fmt.Println("RPC call timed out") } ``` -------------------------------- ### Handle Individual Participant Speaking Events Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/06-callbacks-and-events.md Implement a callback to track when an individual participant starts or stops speaking. This can be used for fine-grained UI control. ```go participantCallback := lksdk.NewParticipantCallback() participantCallback.OnIsSpeakingChanged = func(p lksdk.Participant) { if p.IsSpeaking() { fmt.Printf("%s started speaking\n", p.Name()) } else { fmt.Printf("%s stopped speaking\n", p.Name()) } } ``` -------------------------------- ### ConnectInfo Structure Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Contains information required for establishing a connection, including room details, participant credentials, and metadata. Used during the connection setup process. ```go type ConnectInfo struct { APIKey string APISecret string RoomName string ParticipantName string ParticipantIdentity string ParticipantKind ParticipantKind ParticipantMetadata string ParticipantAttributes map[string]string } ``` -------------------------------- ### Define SampleProvider Interface Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/07-media-apis.md Defines the interface for providing media samples. Implement this to create custom media sources. ```go type SampleProvider interface { NextSample(ctx context.Context) (media.Sample, error) } ``` -------------------------------- ### Configure Pacer for Video Publishing Source: https://github.com/livekit/server-sdk-go/blob/main/README.md Enable a pacer when publishing video to maintain a consistent packet flow and avoid bitrate spikes caused by large keyframes. This example configures a pacer with a target bitrate of 10Mbps and a maximum latency of 1 second. ```go import "github.com/livekit/mediatransportutil/pkg/pacer" // Control total output bitrate to 10Mbps with 1s max latency pf := pacer.NewPacerFactory( pacer.LeakyBucketPacer, pacer.WithBitrate(10000000), pacer.WithMaxLatency(time.Second), ) room, err := lksdk.ConnectToRoom(hostURL, lksdk.ConnectInfo{ APIKey: apiKey, APISecret: apiSecret, RoomName: roomName, ParticipantIdentity: identity, }, &lksdk.RoomCallback{ ParticipantCallback: lksdk.ParticipantCallback{ OnTrackSubscribed: onTrackSubscribed, }, }, lksdk.WithPacer(pf)) ``` -------------------------------- ### Create and Join a New Room Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Demonstrates how to create a new Room instance with event callbacks and join a room. ```go room := lksdk.NewRoom(&lksdk.RoomCallback{ OnParticipantConnected: func(rp *lksdk.RemoteParticipant) { fmt.Printf("Participant joined: %s\n", rp.Identity()) }, }) err := room.Join(url, info) ``` -------------------------------- ### Configure PCMRemoteTrack with Target Sample Rate Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/07-media-apis.md Example of creating a PCM remote track and setting a specific target sample rate for resampling. The default is 48000 Hz. ```go pcmTrack, _ := lkmedia.NewPCMRemoteTrack( remoteTrack, writer, lkmedia.WithTargetSampleRate(16000), // 16 kHz ) ``` -------------------------------- ### Connect to Room and Publish Track Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/INDEX.md Demonstrates how to establish a connection to a LiveKit room and publish a local track. Requires importing the main SDK package. ```go import lksdk "github.com/livekit/server-sdk-go/v2" // Room connection room, _ := lksdk.ConnectToRoom(...) room.LocalParticipant.PublishTrack(...) // Service clients roomClient := lksdk.NewRoomServiceClient(...) egressClient := lksdk.NewEgressClient(...) sipClient := lksdk.NewSIPClient(...) // Callbacks callback := lksdk.NewRoomCallback() partCallback := lksdk.NewParticipantCallback() ``` -------------------------------- ### Publish Audio from PCM Samples Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Initializes a local audio track from PCM samples and publishes it to the room. You'll need to provide sample rate, channels, and a logger. Use `track.WriteSample()` to send audio data. ```go import lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" track, _ := lkmedia.NewPCMLocalTrack(48000, 1, logger) // Write PCM16 samples track.WriteSample(sample) room.LocalParticipant.PublishTrack(track, opts) ``` -------------------------------- ### RemoteParticipant.AudioLevel Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Gets the current audio level of the remote participant. ```APIDOC ## RemoteParticipant.AudioLevel ### Description Returns the current audio level (0.0 to 1.0). ### Method ```go func (p *RemoteParticipant) AudioLevel() float32 ``` ### Returns Float32 audio level. ``` -------------------------------- ### Use Protocol Types and Enums Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/INDEX.md Demonstrates the usage of LiveKit protocol types for requests and grants, as well as protocol enums for track sources and video quality. Import the protocol packages. ```go import "github.com/livekit/protocol/livekit" import "github.com/livekit/protocol/auth" // Types req := &livekit.CreateRoomRequest{Name: "room"} grant := &auth.VideoGrant{RoomJoin: true} // Enums source := livekit.TrackSource_CAMERA quality := livekit.VideoQuality_HIGH ``` -------------------------------- ### Create Room using Protocol Message Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Illustrates creating a LiveKit room using a protobuf message, setting properties like name, empty timeout, and maximum participants. ```go import "github.com/livekit/protocol/livekit" // Create room with protobuf message room, err := roomClient.CreateRoom(ctx, &livekit.CreateRoomRequest{ Name: "my-room", EmptyTimeout: 300, MaxParticipants: 100, Metadata: "{}", }) ``` -------------------------------- ### Get LocalTrackPublication Name Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Retrieves the name of a published local track. ```go func (p *LocalTrackPublication) Name() string ``` -------------------------------- ### Initialize Service Clients with Authentication Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Shows how to initialize various LiveKit service clients, such as Room, Egress, and SIP clients, using API key and secret. These clients are used for server-side room management and features. ```go // Service clients NewRoomServiceClient(url, apiKey, apiSecret) NewEgressClient(url, apiKey, apiSecret) NewSIPClient(url, apiKey, apiSecret) // ... etc ``` -------------------------------- ### Get RemoteTrackPublication Name Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve the name of a remote track publication. ```go func (p *RemoteTrackPublication) Name() string ``` -------------------------------- ### Configure WebRTC Codec and Create Local Track Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/INDEX.md Shows how to define a WebRTC codec capability and create a new local track using it. Requires importing Pion WebRTC and the main SDK package. ```go import "github.com/pion/webrtc/v4" import "github.com/pion/rtcp" // Codec codec := webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8} // Track track, _ := lksdk.NewLocalTrack(codec) ``` -------------------------------- ### Get Room Metadata Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Retrieves the metadata associated with the LiveKit room. ```go func (r *Room) Metadata() string ``` -------------------------------- ### Get Room Name Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Retrieves the name of the current LiveKit room. ```go func (r *Room) Name() string ``` -------------------------------- ### Connect to a LiveKit Room as a Participant Source: https://github.com/livekit/server-sdk-go/blob/main/README.md This snippet demonstrates how to establish a connection to a LiveKit room using the server-SDK-go. It includes setting up API credentials, room details, and participant identity, along with a callback for track subscriptions. Ensure you have the correct host URL, API key, and secret. ```go import ( lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { hostURL := "host-url" // ex: https://project-123456.livekit.cloud apiKey := "api-key" apiSecret := "api-secret" roomName := "myroom" identity := "botuser" roomCB := &lksdk.RoomCallback{ ParticipantCallback: lksdk.ParticipantCallback{ OnTrackSubscribed: trackSubscribed, }, } room, err := lksdk.ConnectToRoom(hostURL, lksdk.ConnectInfo{ APIKey: apiKey, APISecret: apiSecret, RoomName: roomName, ParticipantIdentity: identity, }, roomCB) if err != nil { panic(err) } ... room.Disconnect() } func trackSubscribed(track *webrtc.TrackRemote, publication *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) { } ``` -------------------------------- ### Create Connector Client Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initializes a new client for managing connector integrations. Requires server URL, API key, and secret key. ```go func NewConnectorClient( url string, apiKey string, secretKey string, opts ...twirp.ClientOption, ) *ConnectorClient ``` -------------------------------- ### Get LocalTrackPublication SID Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Retrieves the session ID of a published local track. ```go func (p *LocalTrackPublication) SID() string ``` ```go trackSID := publication.SID() ``` -------------------------------- ### Get RemoteParticipant Permissions Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves the server-side permissions granted to the remote participant. ```go func (p *RemoteParticipant) Permissions() *livekit.ParticipantPermission ``` -------------------------------- ### Create RoomServiceClient Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/02-room-service-client.md Initializes a new RoomServiceClient for server-side room management. Requires the LiveKit server URL, API key, and secret key for authentication. Optional Twirp client options can be provided. ```go roomClient := lksdk.NewRoomServiceClient( "https://livekit.example.com", apiKey, apiSecret, ) ``` -------------------------------- ### Get LocalTrackPublication Kind Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Retrieves the kind (audio or video) of a published local track. ```go func (p *LocalTrackPublication) Kind() TrackKind ``` -------------------------------- ### Create AgentClient Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Creates a new Agent client for managing agent deployments. Returns the client and an error if initialization fails. Requires server URL, API key, and secret key. ```go func NewAgentClient( url string, apiKey string, apiSecret string, opts ...AgentClientOption, ) (*AgentClient, error) ``` ```go agentClient, err := lksdk.NewAgentClient(url, apiKey, apiSecret) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get RemoteTrackPublication Kind Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve the kind (audio or video) of a remote track publication. ```go func (p *RemoteTrackPublication) Kind() TrackKind ``` -------------------------------- ### Connect to a LiveKit Room Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md Demonstrates how to connect to a LiveKit room using provided credentials and set up basic participant event callbacks. Ensure you have the correct URL, API key, and secret for your LiveKit instance. ```go package main import ( "context" "fmt" "log" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { // Configuration url := "https://livekit.example.com" apiKey := "your-api-key" apiSecret := "your-api-secret" roomName := "test-room" identity := "user-123" // Create callback callback := &lksdk.RoomCallback{ OnParticipantConnected: func(rp *lksdk.RemoteParticipant) { fmt.Printf("Participant joined: %s\n", rp.Identity()) }, OnParticipantDisconnected: func(rp *lksdk.RemoteParticipant) { fmt.Printf("Participant left: %s\n", rp.Identity()) }, } // Connect to room room, err := lksdk.ConnectToRoom(url, lksdk.ConnectInfo{ APIKey: apiKey, APISecret: apiSecret, RoomName: roomName, ParticipantIdentity: identity, ParticipantName: "My User", }, callback) if err != nil { log.Fatal(err) } defer room.Disconnect() fmt.Printf("Connected to room: %s\n", room.Name()) // Keep running select {} } ``` -------------------------------- ### Get RemoteTrackPublication SID Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve the unique session ID for a remote track publication. ```go trackSID := publication.SID() ``` -------------------------------- ### Create PCMLocalTrack for Publishing Audio Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/07-media-apis.md Initializes a new PCM local track for publishing audio. Ensure the sample rate and channel count match your audio source. Stereo is not currently supported. ```go import lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" track, err := lkmedia.NewPCMLocalTrack( 48000, // 48kHz sample rate 1, // Mono logger, lkmedia.WithTrackStats(), ) if err != nil { log.Fatal(err) } pub, _ := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "audio", }) ``` -------------------------------- ### Get RemoteParticipant Kind Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Returns the type or kind of the participant (e.g., remote, local). ```go func (p *RemoteParticipant) Kind() ParticipantKind ``` -------------------------------- ### Create IngressClient Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initializes a new Ingress client for managing incoming media streams. Requires server URL, API key, and secret key. ```go func NewIngressClient( url string, apiKey string, secretKey string, opts ...twirp.ClientOption, ) *IngressClient ``` ```go ingressClient := lksdk.NewIngressClient(url, apiKey, apiSecret) ``` -------------------------------- ### Join Room with Connection Info Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Use this method to join a LiveKit room using server URL, connection details, and optional connection configurations. ```go func (r *Room) Join( url string, info ConnectInfo, opts ...ConnectOption, ) error ``` -------------------------------- ### Track Interface Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/08-errors-and-types.md Represents a media track. Provides a method to get the track's unique ID. ```go type Track interface { ID() string } ``` -------------------------------- ### Dial WhatsApp Call Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initiates an outgoing WhatsApp call. Use this to start a new WhatsApp call session. ```go func (c *ConnectorClient) DialWhatsAppCall( ctx context.Context, req *livekit.DialWhatsAppCallRequest, ) (*livekit.DialWhatsAppCallResponse, error) ``` -------------------------------- ### Get RemoteTrackPublication TrackInfo Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve detailed information about the remote track publication in the form of a TrackInfo protobuf message. ```go func (p *RemoteTrackPublication) TrackInfo() *livekit.TrackInfo ``` -------------------------------- ### Create New SIP Client Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Instantiates a new SIP client for managing SIP trunk configurations and call handling. Requires LiveKit server URL, API key, and secret key. ```go func NewSIPClient( url string, apiKey string, secretKey string, opts ...twirp.ClientOption, ) *SIPClient ``` ```go sipClient := lksdk.NewSIPClient(url, apiKey, apiSecret) ``` -------------------------------- ### Get RemoteParticipant Display Name Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves the display name of a remote participant. This is an optional field that can be set by the participant. ```go func (p *RemoteParticipant) Name() string ``` -------------------------------- ### Publish Audio from File Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md Use this snippet to publish an audio file (e.g., OGG) to a LiveKit room. It configures track options like frame duration and a callback for when playback completes. ```go package main import ( "fmt" "log" "time" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { room, _ := connectToRoom() defer room.Disconnect() // Create track from OGG file track, err := lksdk.NewLocalFileTrack("audio.ogg", lksdk.ReaderTrackWithFrameDuration(20 * time.Millisecond), lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("Audio finished") }), ) if err != nil { log.Fatal(err) } // Publish pub, err := room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: "background-audio", Source: livekit.TrackSource_MICROPHONE, }) if err != nil { log.Fatal(err) } fmt.Printf("Published audio: %s\n", pub.SID()) // Wait for playback to complete select {} } ``` -------------------------------- ### Connect to Room and Receive Video Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Establishes a connection to a LiveKit room and sets up a callback for when tracks are subscribed. Ensure you handle the track processing within the callback. ```go room, _ := lksdk.ConnectToRoom(url, info, &lksdk.RoomCallback{ OnTrackSubscribed: func(track *webrtc.TrackRemote, pub *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) { // Process video/audio stream }, }) defer room.Disconnect() ``` -------------------------------- ### Create Agent Dispatch Client Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Initializes a new client for managing agent dispatches. Requires server URL, API key, and secret key. ```go func NewAgentDispatchServiceClient( url string, apiKey string, secretKey string, opts ...twirp.ClientOption, ) *AgentDispatchClient ``` -------------------------------- ### Publish Video Track from File Source: https://github.com/livekit/server-sdk-go/blob/main/README.md Publish a video track from a local file using `NewLocalFileTrack`. Ensure the file is encoded in a compatible format like VP8. Options can control frame duration and provide a callback upon completion. ```go file := "video.ivf" videoWidth := 1920 videoHeight := 1080 track, err := lksdk.NewLocalFileTrack(file, // control FPS to ensure synchronization lksdk.ReaderTrackWithFrameDuration(33 * time.Millisecond), lksdk.ReaderTrackWithOnWriteComplete(func() { fmt.Println("track finished") }), ) if err != nil { return err } if _, err = room.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{ Name: file, VideoWidth: videoWidth, VideoHeight: videoHeight, }); err != nil { return err } ``` -------------------------------- ### Get RemoteParticipant Metadata Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves custom metadata associated with a remote participant. This metadata can be any string, often in JSON format. ```go func (p *RemoteParticipant) Metadata() string ``` -------------------------------- ### Media Options for LiveKit SDK Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Configure media processing, including enabling track and hardware statistics, audio encryption, and resampling for target sample rate and channels. ```go lkmedia.WithTrackStats() lkmedia.WithHWStats() lkmedia.WithEncryptor(encryptor) lkmedia.WithTargetSampleRate(16000) lkmedia.WithTargetChannels(1) ``` -------------------------------- ### Get RemoteParticipant Identity Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves the identity string associated with a remote participant. This is typically a unique identifier provided by the application. ```go func (p *RemoteParticipant) Identity() string ``` -------------------------------- ### Get Disconnect Reason Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Retrieves the reason provided by the server for the room disconnection. Returns a Protobuf DisconnectReason enum value. ```go func (r *Room) DisconnectReason() livekit.DisconnectReason ``` -------------------------------- ### AgentClient Method: DeployAgent Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Deploys an agent using the Agent client. Requires context and a DeployAgentRequest. ```go func (c *AgentClient) DeployAgent( ctx context.Context, req *livekit.DeployAgentRequest, ) (*livekit.DeployAgentResponse, error) ``` -------------------------------- ### Unpublish Track Example Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Remove a previously published track from the room using its track SID. Handle potential errors during unpublishing. ```go err := room.LocalParticipant.UnpublishTrack(trackSID) if err != nil { log.Printf("Error unpublishing: %v", err) } ``` -------------------------------- ### Get RemoteTrackPublication Source Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve the source of a remote track publication, such as CAMERA, MICROPHONE, or SCREEN_SHARE. Use this to identify the origin of the track. ```go source := publication.Source() if source == livekit.TrackSource_SCREEN_SHARE { fmt.Println("This is a screen share") } ``` -------------------------------- ### Connect to Room with Authentication Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Demonstrates how to connect to a LiveKit room using API key and secret for authentication. This is typically used for establishing a client connection to a room. ```go // Room connection ConnectToRoom(url, ConnectInfo{ APIKey: "my-api-key", APISecret: "my-api-secret", // ... }) ``` -------------------------------- ### Get RemoteParticipant Audio Level Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Returns the current audio level of a remote participant, ranging from 0.0 (silent) to 1.0 (loudest). ```go func (p *RemoteParticipant) AudioLevel() float32 ``` -------------------------------- ### Manage LiveKit Rooms and Participants Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/09-complete-examples.md This Go code snippet demonstrates a full lifecycle of room management, including creation, listing participants, muting tracks, updating metadata, and deletion. Ensure you have the server-sdk-go imported and replace placeholder values with your LiveKit server URL and credentials. ```go package main import ( "context" "fmt" "log" "github.com/livekit/protocol/livekit" lksdk "github.com/livekit/server-sdk-go/v2" ) func main() { ctx := context.Background() // Create room service client roomClient := lksdk.NewRoomServiceClient( "https://livekit.example.com", "api-key", "api-secret", ) // Create a room room, err := roomClient.CreateRoom(ctx, &livekit.CreateRoomRequest{ Name: "my-room", EmptyTimeout: 300, // 5 minutes MaxParticipants: 100, }) if err != nil { log.Fatal(err) } fmt.Printf("Created room: %s\n", room.Sid) // List all rooms rooms, err := roomClient.ListRooms(ctx, &livekit.ListRoomsRequest{}) if err != nil { log.Fatal(err) } fmt.Printf("Total rooms: %d\n", len(rooms.Rooms)) // List participants in room participants, err := roomClient.ListParticipants(ctx, &livekit.ListParticipantsRequest{ Room: "my-room", }) if err != nil { log.Fatal(err) } for _, p := range participants.Participants { fmt.Printf("- %s (%s)\n", p.Name, p.Identity) } // Mute a participant's track _, err = roomClient.MutePublishedTrack(ctx, &livekit.MuteRoomTrackRequest{ Room: "my-room", Identity: "user-123", TrackSid: "TR_abc123", Muted: true, }) if err != nil { log.Fatal(err) } // Update participant metadata _, err = roomClient.UpdateParticipant(ctx, &livekit.UpdateParticipantRequest{ Room: "my-room", Identity: "user-123", Metadata: `{"role": "moderator"}`, }) if err != nil { log.Fatal(err) } // Delete the room _, err = roomClient.DeleteRoom(ctx, &livekit.DeleteRoomRequest{ Room: "my-room", }) if err != nil { log.Fatal(err) } fmt.Println("Room deleted") } ``` -------------------------------- ### Get RemoteParticipant Session ID Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves the unique session ID for a remote participant. This ID is assigned when the participant connects to the room. ```go func (p *RemoteParticipant) SID() string ``` -------------------------------- ### Create PCM Local and Remote Tracks Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/INDEX.md Shows how to create PCM (Pulse-Code Modulation) audio tracks using the media package. Import the media sub-package for these functionalities. ```go import lkmedia "github.com/livekit/server-sdk-go/v2/pkg/media" // PCM audio track, _ := lkmedia.NewPCMLocalTrack(...) pcmTrack, _ := lkmedia.NewPCMRemoteTrack(...) ``` -------------------------------- ### Manage LiveKit Rooms with RoomService API Source: https://github.com/livekit/server-sdk-go/blob/main/README.md Demonstrates common RoomService API operations including creating, listing, deleting, and managing participants within LiveKit rooms. ```go import ( lksdk "github.com/livekit/server-sdk-go/v2" livekit "github.com/livekit/protocol/livekit" ) func main() { hostURL := "host-url" // ex: https://project-123456.livekit.cloud apiKey := "api-key" apiSecret := "api-secret" roomName := "myroom" identity := "participantIdentity" roomClient := lksdk.NewRoomServiceClient(hostURL, apiKey, apiSecret) // create a new room room, _ := roomClient.CreateRoom(context.Background(), &livekit.CreateRoomRequest{ Name: roomName, }) // list rooms res, _ := roomClient.ListRooms(context.Background(), &livekit.ListRoomsRequest{}) // terminate a room and cause participants to leave roomClient.DeleteRoom(context.Background(), &livekit.DeleteRoomRequest{ Room: roomName, }) // list participants in a room res, _ := roomClient.ListParticipants(context.Background(), &livekit.ListParticipantsRequest{ Room: roomName, }) // disconnect a participant from room roomClient.RemoveParticipant(context.Background(), &livekit.RoomParticipantIdentity{ Room: roomName, Identity: identity, }) // mute/unmute participant's tracks roomClient.MutePublishedTrack(context.Background(), &livekit.MuteRoomTrackRequest{ Room: roomName, Identity: identity, TrackSid: "track_sid", Muted: true, }) } ``` -------------------------------- ### Get RemoteParticipant Attributes Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieves custom attributes for a remote participant as a map of key-value string pairs. These attributes can be used for custom data. ```go func (p *RemoteParticipant) Attributes() map[string]string ``` -------------------------------- ### Create New EgressClient Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Instantiates a new Egress client with the provided server URL, API key, and secret key. Additional Twirp client options can be passed. ```go func NewEgressClient( url string, apiKey string, secretKey string, opts ...twirp.ClientOption, ) *EgressClient ``` ```go egressClient := lksdk.NewEgressClient(url, apiKey, apiSecret) ``` -------------------------------- ### Write Media Sample to LocalTrack Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/03-local-participant.md Use the WriteSample method to send media data to a local track. This method accepts a media.Sample containing data and metadata. ```go func (t *LocalTrack) WriteSample( sample media.Sample, opts SampleWriteOptions, ) error ``` -------------------------------- ### Get All Remote Participants Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/01-room-connection.md Retrieves a slice containing all remote participants currently connected to the LiveKit room. Useful for iterating through connected users. ```go func (r *Room) GetParticipants() []*RemoteParticipant ``` ```go participants := room.GetParticipants() for _, p := range participants { fmt.Printf("Participant: %s (%s)\n", p.Name(), p.Identity()) } ``` -------------------------------- ### AgentClient Method: CreateAgent Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/05-client-apis.md Creates a new agent deployment using the Agent client. Requires context and a CreateAgentRequest. ```go func (c *AgentClient) CreateAgent( ctx context.Context, req *livekit.CreateAgentRequest, ) (*livekit.CreateAgentResponse, error) ``` -------------------------------- ### Connection Options for LiveKit SDK Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/00-api-overview.md Configure connection-specific behaviors like auto-subscribe, timeouts, retransmission buffers, packet pacing, and single peer connection mode. ```go lksdk.WithAutoSubscribe(true) lksdk.WithConnectTimeout(30*time.Second) lksdk.WithRetransmitBufferSize(512) lksdk.WithPacer(pacerFactory) lksdk.WithSinglePeerConnection() ``` -------------------------------- ### Get Underlying WebRTC Track Source: https://github.com/livekit/server-sdk-go/blob/main/_autodocs/04-remote-participants.md Retrieve the underlying WebRTC track if the participant is subscribed to it. The returned track can be cast to *webrtc.TrackRemote for handling RTP packets. ```go if pub.IsSubscribed() { remoteTrack := pub.Track().(*webrtc.TrackRemote) // Handle RTP packets from remoteTrack } ```