@@ -73,7 +73,7 @@ export function MusicServiceProvider({ children }) {
7373 */
7474 const [ volume , setVolume ] = useState ( musicServiceConfig . DEFAULT_VOLUME ) ;
7575
76- // This effect syncs volume → gain node
76+ // This effect syncs volume → gain node whenever volume changes
7777 useEffect ( ( ) => {
7878 if ( gainNodeRef . current ) {
7979 const fraction = volume / 100 ;
@@ -95,8 +95,7 @@ export function MusicServiceProvider({ children }) {
9595 } )
9696 . then ( ( data ) => {
9797 setMusicList ( data ) ;
98- // Optionally auto-load first track
99- // loadTrackByIndex(0);
98+ // Optionally auto-load first track: loadTrackByIndex(0);
10099 } )
101100 . catch ( ( err ) => {
102101 console . error ( 'Error loading music list:' , err ) ;
@@ -111,16 +110,22 @@ export function MusicServiceProvider({ children }) {
111110 if ( ! audioContextRef . current ) {
112111 const AudioContext = window . AudioContext || window . webkitAudioContext ;
113112 audioContextRef . current = new AudioContext ( ) ;
113+
114114 gainNodeRef . current = audioContextRef . current . createGain ( ) ;
115115 gainNodeRef . current . connect ( audioContextRef . current . destination ) ;
116+
117+ // Immediately set the gain to the default volume so there's no mismatch
118+ const fraction = volume / 100 ;
119+ const exponented = Math . pow ( fraction , musicServiceConfig . VOLUME_EXPONENT ) ;
120+ gainNodeRef . current . gain . setValueAtTime ( exponented , 0 ) ;
116121 }
117122 // If context is suspended, try to resume
118123 if ( audioContextRef . current . state === 'suspended' ) {
119124 audioContextRef . current . resume ( ) . catch ( ( err ) => {
120125 console . warn ( 'AudioContext resume error:' , err ) ;
121126 } ) ;
122127 }
123- } , [ ] ) ;
128+ } , [ volume ] ) ;
124129
125130 /**
126131 * 8) loadTrackByIndex: fetch/ decode the MP3 into an AudioBuffer, set ID3 tags, etc.
@@ -211,7 +216,7 @@ export function MusicServiceProvider({ children }) {
211216 ) ;
212217
213218 /**
214- * 9) Next / Prev must be declared before referencing them inside "play()"
219+ * 9) Next / Prev must be declared before referencing them inside "play()"
215220 */
216221 const handleNext = useCallback ( ( ) => {
217222 if ( ! musicList . length ) return ;
@@ -284,7 +289,8 @@ export function MusicServiceProvider({ children }) {
284289 if ( ! isPlaying ) return ;
285290
286291 // How long we’ve played so far
287- const playedSoFar = pausedAtRef . current + ( performance . now ( ) - startTimestampRef . current ) / 1000 ;
292+ const playedSoFar =
293+ pausedAtRef . current + ( performance . now ( ) - startTimestampRef . current ) / 1000 ;
288294 pausedAtRef . current = playedSoFar ;
289295
290296 // Stop the current source
0 commit comments