Skip to main content

Start Broadcasting

After creating a room, obtain broadcasting credentials and connect to LiveKit to start streaming. This guide covers getting broadcaster data, connecting to LiveKit, and managing the broadcast session.

Prerequisites

Before starting a broadcast, ensure you have:
  1. Created a room - See Create Room for room creation
  2. Created a room post - Link the room to a post for social distribution
  3. Installed LiveKit SDK - Required for streaming connection

Getting Broadcaster Data

Retrieve the streaming credentials needed to connect to LiveKit. The broadcast data contains the connection URL and authentication token.

Broadcast Data Types

TypeDescriptionProperties
CoHostsMulti-host co-streaming sessioncoHostToken, coHostUrl
func getBroadcasterData(roomId: String) async {
    do {
        let broadcastData = try await roomRepository.getBroadcastData(roomId: roomId)
        
        switch broadcastData {
        case .coHosts(let data):
            // Use coHostToken and coHostUrl for multi-host streaming
            let token = data.coHostToken
            let url = data.coHostUrl
            // Connect to LiveKit with these credentials
        }
    } catch {
        // Handle error here
    }
}

Installing LiveKit SDK

Before connecting, install the LiveKit SDK for your platform:
// Add via Swift Package Manager:
// https://github.com/livekit/client-sdk-swift

// Also add camera and microphone permissions to Info.plist:
// NSCameraUsageDescription
// NSMicrophoneUsageDescription

Connecting to LiveKit

Use the coHostUrl as the WebSocket URL and the coHostToken as the access token to establish the streaming connection.
import LiveKit

func connectToLiveKit(coHostUrl: String, coHostToken: String) async {
    // Create LiveKit Room instance (not to be confused with AmityRoom)
    let liveKitRoom = Room()
    
    do {
        try await liveKitRoom.connect(url: coHostUrl, token: coHostToken)
        print("Connected to LiveKit room successfully")
        
        // Access local participant after connection
        let localParticipant = liveKitRoom.localParticipant
        
        // Start publishing audio/video tracks
        try await localParticipant.setCamera(enabled: true)
        try await localParticipant.setMicrophone(enabled: true)
    } catch {
        print("Failed to connect: \(error.localizedDescription)")
    }
}

Complete Broadcasting Flow

Here’s the complete workflow from room creation to starting the broadcast:
import AmitySDK
import LiveKit

class BroadcastManager {
    private var liveKitRoom: Room?
    
    func startBroadcast(roomId: String) async {
        do {
            // 1. Get broadcaster credentials
            let broadcastData = try await roomRepository.getBroadcastData(roomId: roomId)
            
            guard case .coHosts(let data) = broadcastData else {
                print("Invalid broadcast data type")
                return
            }
            
            // 2. Create LiveKit room instance
            liveKitRoom = Room()
            
            // 3. Connect to LiveKit
            try await liveKitRoom?.connect(url: data.coHostUrl, token: data.coHostToken)
            print("Connected to LiveKit successfully")
            
            // 4. Enable camera and microphone
            try await liveKitRoom?.localParticipant.setCamera(enabled: true)
            try await liveKitRoom?.localParticipant.setMicrophone(enabled: true)
            
            print("Broadcasting started!")
        } catch {
            print("Failed to start broadcast: \(error)")
        }
    }
    
    func stopBroadcast() async {
        await liveKitRoom?.disconnect()
        liveKitRoom = nil
        print("Broadcast stopped")
    }
}

Stopping the Broadcast

To end the broadcast, disconnect from LiveKit and optionally stop the room:
// Disconnect from LiveKit
await liveKitRoom.disconnect()

// Optionally stop the room to prevent reconnection
try await roomRepository.stopRoom(roomId: roomId)

Connection Event Handling

Handle connection events for a robust streaming experience:
import LiveKit

class BroadcastEventHandler: RoomDelegate {
    
    func room(_ room: Room, didConnect isReconnect: Bool) {
        print(isReconnect ? "Reconnected to room" : "Connected to room")
        updateUI(state: .connected)
    }
    
    func room(_ room: Room, didDisconnect error: Error?) {
        if let error = error {
            print("Disconnected with error: \(error.localizedDescription)")
            handleDisconnectionError(error)
        } else {
            print("Disconnected cleanly")
        }
        updateUI(state: .disconnected)
    }
    
    func room(_ room: Room, didUpdate connectionState: ConnectionState) {
        switch connectionState {
        case .connecting:
            updateUI(state: .connecting)
        case .connected:
            updateUI(state: .connected)
        case .reconnecting:
            updateUI(state: .reconnecting)
        case .disconnected:
            updateUI(state: .disconnected)
        }
    }
    
    func room(_ room: Room, participant: LocalParticipant, didPublish publication: LocalTrackPublication) {
        print("Published track: \(publication.kind)")
    }
}

Best Practices

  • Test camera and microphone before going live
  • Verify network connectivity and bandwidth
  • Check permissions are granted on mobile devices
  • Preview video before starting the broadcast
  • Monitor connection quality indicators
  • Handle reconnection events gracefully
  • Provide visual feedback for connection states
  • Keep the app in foreground for best performance
  • Disconnect from LiveKit cleanly
  • Call stopRoom() to finalize the broadcast
  • Allow time for recording processing if enabled
  • Notify viewers that the broadcast has ended
For detailed setup instructions, event handling, and advanced features, refer to the official LiveKit documentation.

Troubleshooting

Problem: Unable to connect to LiveKitSolutions:
  • Verify coHostToken hasn’t expired
  • Check network connectivity
  • Ensure camera/microphone permissions are granted
  • Validate the coHostUrl is correct
Problem: Camera or microphone not publishingSolutions:
  • Check device permissions are granted
  • Verify no other app is using the camera
  • Try toggling tracks off and on again
  • Restart the connection
Problem: Constantly reconnectingSolutions:
  • Check network stability
  • Monitor bandwidth availability
  • Consider reducing video quality
  • Check for background app restrictions

Next Steps