refined-toddler-89382
08/08/2025, 7:45 AMpublic async createAndConnectRoom(userName?: string, version?: string) {
try {
const queryOptions: { ROOM_NAME: string, USER_NAME?: string, VERSION?: string } = {
ROOM_NAME: this.roomName
}
// Only add 'name' if userName is not null or empty
if (userName && userName.trim() !== '') {
queryOptions.USER_NAME = userName
}
queryOptions.VERSION = version ?? 'prod'
const query = new URLSearchParams(queryOptions)
console.log('Trying to retrieve LiveKit Token...')
const response = await fetch(`/api/liveKitToken?${query}`)
if (!response.ok) {
throw new Error(`Failed to fetch token: ${response.statusText}`)
}
this.liveKitToken = await response.text()
}
catch (error) {
this.logAndSend(`Error retrieving LiveKit token: ${error}`)
}
if (this.liveKitToken === undefined) {
this.logAndSend('Failed to retrieve LiveKit token!')
return
}
console.log('Retrieved LiveKit Token.')
try {
// Register VoicePipeline Agent Readyness
this.registerAgentReady()
let url = this.productionUrl
switch (version) {
case 'test':
url = this.testUrl
break
case 'dev':
url = this.devUrl
break
default:
url = this.productionUrl
break
}
console.log(`Connecting to LiveKit room at ${url} with environment: ${version ?? 'prod'}`)
await this.room.connect(url, this.liveKitToken)
// Set up event listeners after connecting
this.setupParticipantEventListeners()
// Handle already connected participants (e.g., TTS agent)
console.log(this.room.remoteParticipants.size + ' remote participants already connected')
this.room.remoteParticipants.forEach((participant) => {
this.setupVoicePipelineAgent(participant)
})
}
catch (error) {
this.logAndSend(`Error connecting to LiveKit room: ${error}`)
}
}
1a.:
private setupParticipantEventListeners() {
// Listener for transcriptions received
this.room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
const info = reader.info
if (info.attributes !== undefined) {
const transcriptionId = info.attributes['lk.transcribed_track_id']
const transcriptionFinal = info.attributes['lk.transcription_final'] === 'true'
const participantIdentity = participantInfo.identity
// Option 1: Process the stream incrementally using a for-await loop.
for await (const chunk of reader) {
// Process only if the transcription is from your own participant
if (participantIdentity === this.room.localParticipant.identity) {
// STT
this.onOwnTranscriptionReceivedListeners.forEach(listener =>
listener(chunk, transcriptionFinal, transcriptionId)
)
}
else {
// TTS
this.onForeignTranscriptionReceivedListeners.forEach(listener =>
listener(chunk, transcriptionFinal, transcriptionId)
)
}
}
// TTS finished
if (participantInfo.identity !== this.room.localParticipant.identity) {
this.onForeignTranscriptionReceivedListeners.forEach(listener =>
listener(undefined, true, transcriptionId)
)
}
}
})
}
1b.:
private setupVoicePipelineAgent(participant: RemoteParticipant) {
console.log('Setting up VoicePipeLine-Agent:', participant.identity)
// Listener for track subscriptions
participant.on(
ParticipantEvent.TrackSubscribed,
(track/* , publication */) => {
if (track.kind === Track.Kind.Audio) {
this.handleTTSAudioTrack(track as RemoteAudioTrack)
}
}
)
// Listener for track unsubscriptions
participant.on(
ParticipantEvent.TrackUnsubscribed,
(track/* , publication */) => {
if (track.kind === Track.Kind.Audio) {
this.cleanupTTSAudioTrack(track as RemoteAudioTrack)
}
}
)
// Subscribe to existing audio tracks
participant.trackPublications.forEach((publication: TrackPublication) => {
if (
publication.track
&& publication.track.kind === Track.Kind.Audio
&& publication.isSubscribed
) {
this.handleTTSAudioTrack(publication.track as RemoteAudioTrack)
}
})
}
2.:
public async publishMicrophoneTrack() {
if (this.room.state !== ConnectionState.Connected) {
this.logAndSend('Not connected to room yet!')
return
}
try {
// This will prompt the user for microphone permissions
this.microphoneTrack = await createLocalAudioTrack()
// Publish the track if permission is granted
const audioTrack = await this.room.localParticipant.publishTrack(this.microphoneTrack, { name: 'microphone' })
this.publishedAudioTracks.set('microphone', audioTrack)
console.log('Microphone access granted and track published.')
}
catch (error) {
this.logAndSend(`Microphone access denied: ${error}`)
}
}
3.:
public async toggleMicrophoneEnabled(enabled: boolean) {
if (this.microphoneTrack !== undefined) {
await this.room.localParticipant.setMicrophoneEnabled(enabled)
}
else {
this.logAndSend('No microphone track to toggle!')
}
}
-> Of course I await all functions.
I even added this when the User clicks the play button:
await this.room.startAudio()
But it did not help either.
It only plays the sound if either the user selects very quickly the microphone permission or if he just reloads the page (after set microphone permission).