play audio on web on start

This commit is contained in:
2026-11-08 20:52:03 +03:00
parent 5de55fd152
commit 9ffceb91ed
3 changed files with 33 additions and 1 deletions

View File

@@ -15,6 +15,7 @@
;; NULL when no music is playing ;; NULL when no music is playing
(var current-music (* Music) NULL) (var current-music (* Music) NULL)
(var audio-unlocked bool false)
(fn load-sound ((file (* const char))) Sound (fn load-sound ((file (* const char))) Sound
(var sound Sound (LoadSound file)) (var sound Sound (LoadSound file))
@@ -70,7 +71,24 @@
(pub fn audio-play-fishing-music () void (pub fn audio-play-fishing-music () void
(switch-music (& fishing-music))) (switch-music (& fishing-music)))
;; Browsers keep the audio context suspended until the first user gesture.
;; Restart the current track once after that gesture so the music actually begins.
#+emscripten
(pub fn audio-unlock () void
(if audio-unlocked
(return))
(= audio-unlocked true)
(if (!= current-music NULL)
(do
(StopMusicStream (* current-music))
(PlayMusicStream (* current-music)))))
#-emscripten
(pub fn audio-unlock () void
(return))
(pub fn audio-play-menu-click () void (pub fn audio-play-menu-click () void
(audio-unlock)
(if (IsSoundValid menu-click) (if (IsSoundValid menu-click)
(PlaySound menu-click))) (PlaySound menu-click)))

View File

@@ -67,7 +67,10 @@
(= clicked true) (= clicked true)
(.quit (. state app-state)))) (.quit (. state app-state))))
;; Any menu key press is a UI interaction too ;; Any menu key press or click is a UI interaction too
(var key-pressed bool (!= 0 (GetKeyPressed))) (var key-pressed bool (!= 0 (GetKeyPressed)))
(var mouse-pressed bool (IsMouseButtonPressed MOUSE-BUTTON-LEFT))
(if (|| mouse-pressed key-pressed)
(audio-unlock))
(if (|| clicked key-pressed) (if (|| clicked key-pressed)
(audio-play-menu-click))) (audio-play-menu-click)))

View File

@@ -47,6 +47,17 @@
<canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"></canvas> <canvas id="canvas" tabindex="-1" oncontextmenu="event.preventDefault()"></canvas>
<p>Instructions go here.</p> <p>Instructions go here.</p>
<script> <script>
// Browsers suspend audio until the first user gesture. miniaudio only
// installs click/touchend handlers, so make keyboard/pointer input
// unlock the audio context too.
const unlockEvents = ['keydown', 'pointerdown'];
const unlockAudio = () => {
if (!window.miniaudio || typeof window.miniaudio.unlock !== 'function') return;
window.miniaudio.unlock();
unlockEvents.forEach((type) => removeEventListener(type, unlockAudio, true));
};
unlockEvents.forEach((type) => addEventListener(type, unlockAudio, true));
var Module = { var Module = {
canvas: document.getElementById('canvas'), canvas: document.getElementById('canvas'),
print: console.log.bind(console), print: console.log.bind(console),