@@ -12,6 +12,7 @@ export const useSoundPlayer = (props: {
12
12
} ) => {
13
13
const [ isPlaying , setIsPlaying ] = useState ( false ) ;
14
14
const [ isAudioMuted , setIsAudioMuted ] = useState ( false ) ;
15
+ const [ volume , setVolumeState ] = useState < number > ( 1.0 ) ;
15
16
const [ fft , setFft ] = useState < number [ ] > ( generateEmptyFft ( ) ) ;
16
17
17
18
const audioContext = useRef < AudioContext | null > ( null ) ;
@@ -171,6 +172,7 @@ export const useSoundPlayer = (props: {
171
172
isProcessing . current = false ;
172
173
setIsPlaying ( false ) ;
173
174
setIsAudioMuted ( false ) ;
175
+ setVolumeState ( 1.0 ) ;
174
176
175
177
if ( frequencyDataIntervalId . current ) {
176
178
window . clearInterval ( frequencyDataIntervalId . current ) ;
@@ -218,6 +220,20 @@ export const useSoundPlayer = (props: {
218
220
setFft ( generateEmptyFft ( ) ) ;
219
221
} , [ ] ) ;
220
222
223
+ const setVolume = useCallback (
224
+ ( newLevel : number ) => {
225
+ const clampedLevel = Math . max ( 0 , Math . min ( newLevel , 1.0 ) ) ;
226
+ setVolumeState ( clampedLevel ) ;
227
+ if ( gainNode . current && audioContext . current && ! isAudioMuted ) {
228
+ gainNode . current . gain . setValueAtTime (
229
+ clampedLevel ,
230
+ audioContext . current . currentTime ,
231
+ ) ;
232
+ }
233
+ } ,
234
+ [ isAudioMuted ] ,
235
+ ) ;
236
+
221
237
const muteAudio = useCallback ( ( ) => {
222
238
if ( gainNode . current && audioContext . current ) {
223
239
gainNode . current . gain . setValueAtTime ( 0 , audioContext . current . currentTime ) ;
@@ -227,10 +243,13 @@ export const useSoundPlayer = (props: {
227
243
228
244
const unmuteAudio = useCallback ( ( ) => {
229
245
if ( gainNode . current && audioContext . current ) {
230
- gainNode . current . gain . setValueAtTime ( 1 , audioContext . current . currentTime ) ;
246
+ gainNode . current . gain . setValueAtTime (
247
+ volume ,
248
+ audioContext . current . currentTime ,
249
+ ) ;
231
250
setIsAudioMuted ( false ) ;
232
251
}
233
- } , [ ] ) ;
252
+ } , [ volume ] ) ;
234
253
235
254
return {
236
255
addToQueue,
@@ -243,5 +262,7 @@ export const useSoundPlayer = (props: {
243
262
stopAll,
244
263
clearQueue,
245
264
queueLength,
265
+ volume,
266
+ setVolume,
246
267
} ;
247
268
} ;
0 commit comments