-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSoundContext.tsx
More file actions
63 lines (50 loc) · 1.74 KB
/
SoundContext.tsx
File metadata and controls
63 lines (50 loc) · 1.74 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
53
54
55
56
57
58
59
60
61
62
63
import React, { createContext, useContext, useState, useEffect } from 'react';
import { SoundType } from '../../shared/types';
interface SoundContextType {
playSound: (type: SoundType) => void;
setEnabled: (enabled: boolean) => void;
isEnabled: boolean;
}
const defaultSoundContext: SoundContextType = {
playSound: () => {},
setEnabled: () => {},
isEnabled: true
};
export const SoundContext = createContext<SoundContextType>(defaultSoundContext);
interface SoundProviderProps {
children: React.ReactNode;
}
export const SoundProvider: React.FC<SoundProviderProps> = ({ children }) => {
const [isEnabled, setIsEnabled] = useState(true);
const [sounds, setSounds] = useState<Map<SoundType, HTMLAudioElement>>(new Map());
// 初始化音效
useEffect(() => {
const soundMap = new Map<SoundType, HTMLAudioElement>();
// 在实际应用中,这里会加载真实的音效文件
// 目前使用空的Audio对象作为占位符
soundMap.set(SoundType.CLICK, new Audio());
soundMap.set(SoundType.MODULE_SWITCH, new Audio());
soundMap.set(SoundType.CONFIRM, new Audio());
soundMap.set(SoundType.ERROR, new Audio());
setSounds(soundMap);
}, []);
// 播放音效
const playSound = (type: SoundType) => {
if (!isEnabled) return;
const sound = sounds.get(type);
if (sound) {
sound.currentTime = 0;
sound.play().catch(err => console.error('播放音效失败:', err));
}
};
// 设置音效开关
const setEnabled = (enabled: boolean) => {
setIsEnabled(enabled);
};
return (
<SoundContext.Provider value={{ playSound, setEnabled, isEnabled }}>
{children}
</SoundContext.Provider>
);
};
export const useSound = () => useContext(SoundContext);