@@ -686,12 +686,21 @@ export class Player {
686686 | null
687687 | undefined
688688 const audioStream = conn ?. audioStream as
689- | ( AudioResource & { destroyed ?: boolean } )
689+ | ( AudioResource & {
690+ destroyed ?: boolean
691+ _cleanupListeners ?: ( ) => void
692+ } )
690693 | undefined
691694 | null
692695
693696 if ( ! audioStream ) return
694697
698+ try {
699+ audioStream . _cleanupListeners ?.( )
700+ } catch {
701+ // Ignore cleanup errors
702+ }
703+
695704 try {
696705 audioStream . destroy ?.( )
697706 } catch ( err ) {
@@ -941,30 +950,48 @@ export class Player {
941950 if ( typeof ( fetchedStream as { on ?: unknown } ) . on === 'function' ) {
942951 const eventStream = fetchedStream as unknown as VoiceAudioStream
943952 const profilerTap = new PassThrough ( )
944- profilerTap . on ( 'data' , ( chunk : Buffer | Uint8Array | string ) => {
953+ const profilerHandler = ( chunk : Buffer | Uint8Array | string ) => {
945954 const size =
946955 typeof chunk === 'string'
947956 ? Buffer . byteLength ( chunk )
948957 : Number ( ( chunk as { length ?: number } ) ?. length || 0 )
949958 if ( size > 0 ) this . profilerStreamStats . downloadedBytes += size
950959 this . profilerStreamStats . lastChunkAt = Date . now ( )
951- } )
960+ }
961+ profilerTap . on ( 'data' , profilerHandler )
952962 streamForResource = ( fetchedStream as Readable ) . pipe ( profilerTap )
953963 ; ( profilerTap as unknown as Record < string , unknown > ) . _sourceStream =
954964 fetchedStream
955965
956- eventStream . on ?. ( 'eternalboxJump' , ( data : unknown ) => {
966+ const eternalboxHandler = ( data : unknown ) => {
957967 this . emitEvent ( GatewayEvents . ETERNALBOX_JUMP , {
958968 track : this . holoTrack || this . track ,
959969 eternalbox : data
960970 } )
961- } )
962- eventStream . on ?. ( 'icyMetadata' , ( data : unknown ) => {
971+ }
972+ const icyHandler = ( data : unknown ) => {
963973 this . emitEvent ( GatewayEvents . STREAM_METADATA , {
964974 track : this . holoTrack || this . track ,
965975 stream : data
966976 } )
967- } )
977+ }
978+ eventStream . on ?.( 'eternalboxJump' , eternalboxHandler )
979+ eventStream . on ?.( 'icyMetadata' , icyHandler )
980+
981+ const cleanupListeners = ( ) => {
982+ eventStream . off ?.( 'eternalboxJump' , eternalboxHandler )
983+ eventStream . off ?.( 'icyMetadata' , icyHandler )
984+ profilerTap . off ( 'data' , profilerHandler )
985+ profilerTap . destroy ( )
986+ }
987+
988+ streamForResource . on ( 'close' , cleanupListeners )
989+ streamForResource . on ( 'error' , cleanupListeners )
990+ ; (
991+ streamForResource as unknown as {
992+ _cleanupListeners ?: ( ) => void
993+ }
994+ ) . _cleanupListeners = cleanupListeners
968995 }
969996 const resource = audioResourceFactory (
970997 this . guildId ,
0 commit comments