|
|
|
import base64 |
|
from pathlib import Path |
|
from typing import Dict |
|
|
|
|
|
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 = [] |
|
|
|
|
|
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>' |
|
) |
|
|
|
|
|
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>' |
|
) |
|
|
|
|
|
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);" |
|
} |