JoyStroy / sounds.py
Rathapoom's picture
Update sounds.py
8100c93 verified
# 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);"
}