-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseSoundEffects.jsx
More file actions
52 lines (44 loc) · 1.22 KB
/
Copy pathuseSoundEffects.jsx
File metadata and controls
52 lines (44 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useState, useCallback } from "react";
import {
playSoundType,
getSoundEnabled,
setSoundEnabled,
} from "../utils/soundUtils";
import { useIsMobile } from "./useIsMobile";
const SoundContext = createContext(null);
export const SoundProvider = ({ children }) => {
const isMobile = useIsMobile();
const [isSoundEnabled, setIsSoundEnabled] = useState(() => getSoundEnabled());
const toggleSound = useCallback(() => {
setIsSoundEnabled((prev) => {
const newValue = !prev;
setSoundEnabled(newValue);
return newValue;
});
}, []);
const playSound = useCallback(
(soundType, volume = 0.3) => {
if (isMobile) return;
if (isSoundEnabled) {
playSoundType(soundType, volume);
}
},
[isSoundEnabled, isMobile]
);
const value = {
isSoundEnabled,
toggleSound,
playSound,
};
return (
<SoundContext.Provider value={value}>{children}</SoundContext.Provider>
);
};
export const useSoundEffects = () => {
const context = useContext(SoundContext);
if (!context) {
throw new Error("useSoundEffects must be used within a SoundProvider");
}
return context;
};