File size: 3,057 Bytes
477d8ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8100c93
 
477d8ef
8100c93
 
 
 
 
 
 
477d8ef
8100c93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477d8ef
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
# sounds.py
import base64
from pathlib import Path
from typing import Dict

# Audio file paths (ตั้งชื่อไฟล์แบบนี้)
AUDIO_PATHS = {
    'bgm': 'assets/audio/gentle_story.mp3',     # เพลงพื้นหลังแนวนิทาน
    'submit': 'assets/audio/pop.mp3',           # เสียงปุ่มกด
    'achievement': 'assets/audio/chime.mp3',    # เสียงได้รางวัล
    'complete': 'assets/audio/success.mp3'      # เสียงจบเรื่อง
}

class AudioManager:
    def __init__(self):
        self._audio_cache: Dict[str, str] = {}
        self._initialize_cache()
    
    def _initialize_cache(self):
        """Load and cache audio files"""
        for name, path in AUDIO_PATHS.items():
            try:
                with open(path, "rb") as f:
                    audio_bytes = f.read()
                    self._audio_cache[name] = base64.b64encode(audio_bytes).decode()
            except Exception as e:
                print(f"Error loading audio {name}: {e}")

    def get_audio_html(self) -> str:
        """Generate HTML for all audio elements"""
        try:
            audio_elements = []
            
            # Background music (with loop)
            if 'bgm' in self._audio_cache:
                audio_elements.append(
                    f'<audio id="bgm" loop preload="auto" style="display:none;">'
                    f'<source src="data:audio/mp3;base64,{self._audio_cache["bgm"]}" type="audio/mp3">'
                    f'</audio>'
                )
            
            # Sound effects (without loop)
            for name, base64_data in self._audio_cache.items():
                if name != 'bgm':
                    audio_elements.append(
                        f'<audio id="sound_{name}" preload="auto" style="display:none;">'
                        f'<source src="data:audio/mp3;base64,{base64_data}" type="audio/mp3">'
                        f'</audio>'
                    )
            
            # Add JavaScript controls in a more concise way
            audio_elements.append("""
                <script>
                const playSound=e=>{const t=document.getElementById(e);t&&(t.currentTime=0,t.play())},
                toggleBGM=e=>{const t=document.getElementById("bgm");t&&(e?t.play():t.pause())},
                setVolume=e=>{document.getElementsByTagName("audio").forEach(t=>t.volume=e)};
                </script>
            """.strip())
            
            return "\n".join(audio_elements)
            
        except Exception as e:
            logging.error(f"Error generating audio HTML: {str(e)}")
            return ""

def get_sound_commands() -> Dict[str, str]:
    """Get JavaScript commands for playing sounds"""
    return {
        'submit': "playSound('sound_submit');",
        'achievement': "playSound('sound_achievement');",
        'complete': "playSound('sound_complete');",
        'bgm_play': "toggleBGM(true);",
        'bgm_pause': "toggleBGM(false);"
    }