fix(voice): simplify RemoteAudioTrack — remove stale listener race
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useVoiceStore } from '../stores/voice.ts';
|
||||
import { Track } from 'livekit-client';
|
||||
import { Track, RoomEvent } from 'livekit-client';
|
||||
import type { Participant, TrackPublication, Room } from 'livekit-client';
|
||||
|
||||
function RemoteAudioTrack({ participant, room }: { participant: Participant; room: Room }) {
|
||||
@@ -12,7 +12,7 @@ function RemoteAudioTrack({ participant, room }: { participant: Participant; roo
|
||||
|
||||
let pub: TrackPublication | undefined;
|
||||
|
||||
const attachTrack = () => {
|
||||
const attachIfReady = () => {
|
||||
pub = participant.getTrackPublication(Track.Source.Microphone);
|
||||
if (pub?.track && el) {
|
||||
pub.track.attach(el);
|
||||
@@ -20,36 +20,21 @@ function RemoteAudioTrack({ participant, room }: { participant: Participant; roo
|
||||
}
|
||||
};
|
||||
|
||||
const detachTrack = () => {
|
||||
if (pub?.track && el) {
|
||||
pub.track.detach(el);
|
||||
}
|
||||
};
|
||||
// ponytail: check immediately — track may already be subscribed
|
||||
attachIfReady();
|
||||
|
||||
attachTrack();
|
||||
|
||||
const handlePublished = (publication: TrackPublication) => {
|
||||
if (publication.source === Track.Source.Microphone && publication.track) {
|
||||
publication.track.attach(el);
|
||||
el.play().catch(() => {});
|
||||
}
|
||||
};
|
||||
|
||||
room.on('trackPublished' as any, handlePublished);
|
||||
|
||||
// If a track is subscribed later
|
||||
const handleSubscribed = (track: Track, publication: TrackPublication, trackParticipant: Participant) => {
|
||||
if (trackParticipant.identity === participant.identity && publication.source === Track.Source.Microphone) {
|
||||
// ponytail: also listen for delayed subscription
|
||||
const handleSubscribed = (track: Track, _pub: TrackPublication, p: Participant) => {
|
||||
if (p.identity === participant.identity && _pub.source === Track.Source.Microphone) {
|
||||
track.attach(el);
|
||||
el.play().catch(() => {});
|
||||
}
|
||||
};
|
||||
room.on('trackSubscribed' as any, handleSubscribed);
|
||||
room.on(RoomEvent.TrackSubscribed, handleSubscribed);
|
||||
|
||||
return () => {
|
||||
detachTrack();
|
||||
room.off('trackPublished' as any, handlePublished);
|
||||
room.off('trackSubscribed' as any, handleSubscribed);
|
||||
if (pub?.track) pub.track.detach(el);
|
||||
room.off(RoomEvent.TrackSubscribed, handleSubscribed);
|
||||
};
|
||||
}, [participant, room]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user