Skip to content

Commit

Permalink
Merge pull request #8 from agencyenterprise/post-connect-avatar-insta…
Browse files Browse the repository at this point in the history
…nces-support

Support for <Avatar> instances created AFTER 'connect'
  • Loading branch information
nilton-neto authored Jul 30, 2024
2 parents 69a7637 + 6f66ce7 commit 66f6068
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/hooks/useWebAvatar.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RoomEvent, Track } from 'livekit-client';
import { ConnectionState, RoomEvent, Track } from 'livekit-client';
import { useEffect, useRef, useState } from 'react';

import type { RemoteTrack } from 'livekit-client';
Expand All @@ -17,12 +17,16 @@ export function useWebAvatar() {
}

function handleTrackSubscribed(track: RemoteTrack) {
if (track.kind === Track.Kind.Video) {
if (
track.kind === Track.Kind.Video &&
!track.attachedElements.includes(videoRef.current!)
) {
track.attach(videoRef.current!);
} else if (
audioRef &&
track.kind === Track.Kind.Audio &&
room?.canPlaybackAudio
room?.canPlaybackAudio &&
!track.attachedElements.includes(audioRef.current!)
) {
track.attach(audioRef.current!);
}
Expand All @@ -39,14 +43,29 @@ export function useWebAvatar() {
room
.on(RoomEvent.TrackSubscribed, handleTrackSubscribed)
.on(RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed)
.on(RoomEvent.AudioPlaybackStatusChanged, handleAudioPlaybackStatusChanged)
.on(
RoomEvent.AudioPlaybackStatusChanged,
handleAudioPlaybackStatusChanged,
);

if (room.state === ConnectionState.Connected) {
// support for <Avatar> instances created AFTER "connect" by making sure the new video and audio elements are attached
room.remoteParticipants.forEach((participant) => {
participant.trackPublications.forEach(({ track }) => {
handleTrackSubscribed(track!);
});
});
}

return () => {
room
.off(RoomEvent.TrackSubscribed, handleTrackSubscribed)
.off(RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed)
.off(RoomEvent.AudioPlaybackStatusChanged, handleAudioPlaybackStatusChanged);
}
.off(
RoomEvent.AudioPlaybackStatusChanged,
handleAudioPlaybackStatusChanged,
);
};
}, [room]);

return { ...avatar, videoRef, audioRef, canPlaybackAudio };
Expand Down

0 comments on commit 66f6068

Please sign in to comment.