1+ import { StateStore } from 'stream-chat' ;
2+
13import { AudioPlayer , AudioPlayerOptions } from './audio-player' ;
24
35export type AudioPlayerPoolOptions = {
46 allowConcurrentAudioPlayback : boolean ;
57} ;
68
9+ export type AudioPlayerPoolState = {
10+ activeAudioPlayer : AudioPlayer | null ;
11+ } ;
12+
713export class AudioPlayerPool {
814 pool : Map < string , AudioPlayer > ;
915 allowConcurrentAudioPlayback : boolean ;
10- private currentlyPlayingId : string | null = null ;
16+ state : StateStore < AudioPlayerPoolState > = new StateStore < AudioPlayerPoolState > ( {
17+ activeAudioPlayer : null ,
18+ } ) ;
1119
1220 constructor ( { allowConcurrentAudioPlayback } : AudioPlayerPoolOptions ) {
1321 this . pool = new Map < string , AudioPlayer > ( ) ;
@@ -30,15 +38,24 @@ export class AudioPlayerPool {
3038 return newPlayer ;
3139 }
3240
41+ setActivePlayer ( activeAudioPlayer : AudioPlayer | null ) {
42+ this . state . partialNext ( {
43+ activeAudioPlayer,
44+ } ) ;
45+ }
46+
47+ getActivePlayer ( ) {
48+ return this . state . getLatestValue ( ) . activeAudioPlayer ;
49+ }
50+
3351 removePlayer ( id : string ) {
3452 const player = this . pool . get ( id ) ;
3553 if ( ! player ) return ;
3654 player . onRemove ( ) ;
3755 this . pool . delete ( id ) ;
3856
39- // Clear tracking if this was the currently playing player
40- if ( ! this . allowConcurrentAudioPlayback && this . currentlyPlayingId === id ) {
41- this . currentlyPlayingId = null ;
57+ if ( this . getActivePlayer ( ) ?. id === id ) {
58+ this . setActivePlayer ( null ) ;
4259 }
4360 }
4461
@@ -52,24 +69,26 @@ export class AudioPlayerPool {
5269 for ( const player of this . pool . values ( ) ) {
5370 this . removePlayer ( player . id ) ;
5471 }
55- this . currentlyPlayingId = null ;
72+ this . setActivePlayer ( null ) ;
5673 }
5774
5875 requestPlay ( id : string ) {
5976 if ( this . allowConcurrentAudioPlayback ) return ;
6077
61- if ( this . currentlyPlayingId && this . currentlyPlayingId !== id ) {
62- const currentPlayer = this . pool . get ( this . currentlyPlayingId ) ;
78+ if ( this . getActivePlayer ( ) ?. id !== id ) {
79+ const currentPlayer = this . getActivePlayer ( ) ;
6380 if ( currentPlayer && currentPlayer . isPlaying ) {
6481 currentPlayer . pause ( ) ;
6582 }
6683 }
67- this . currentlyPlayingId = id ;
68- }
6984
70- notifyPaused ( id : string ) {
71- if ( this . currentlyPlayingId === id ) {
72- this . currentlyPlayingId = null ;
85+ const activePlayer = this . pool . get ( id ) ;
86+ if ( activePlayer ) {
87+ this . setActivePlayer ( activePlayer ) ;
7388 }
7489 }
90+
91+ notifyPaused ( ) {
92+ this . setActivePlayer ( null ) ;
93+ }
7594}
0 commit comments