Skip to content

Commit 8bdde2b

Browse files
committed
feat(general): handle sound on multiple canvas and scenes
1 parent 7841ada commit 8bdde2b

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

packages/library/src/core/Scene.tsx

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React, { useEffect, useRef } from 'react';
2-
import { Scene as BabylonScene, SceneOptions, WebXRDefaultExperienceOptions, HavokPlugin, Vector3, Nullable, Camera } from '@babylonjs/core';
2+
import { Scene as BabylonScene, SceneOptions, WebXRDefaultExperienceOptions, HavokPlugin, Vector3, Nullable, Camera, Engine } from '@babylonjs/core';
33
import { GUI3DManager } from '@babylonjs/gui';
44
import HavokPhysics from '@babylonjs/havok';
55
import { SceneContext, Store, createBabylonStore } from './store';
@@ -85,12 +85,34 @@ export const Scene: React.FC<SceneProps> = ({ children, sceneOptions, onSceneRea
8585
engine.registerView(canvas, scene.activeCamera as Camera);
8686
}
8787
scene.detachControl();
88-
8988
canvas.onclick = () => {
89+
if (!activeScene) {
90+
// disable audio on all scenes but no current
91+
engine.scenes.forEach(_scene => {
92+
if (_scene !== scene) {
93+
if (_scene.audioEnabled) {
94+
_scene.audioEnabled = false;
95+
}
96+
}
97+
});
98+
}
9099
if (activeScene !== scene) {
100+
if (activeScene?.audioEnabled) {
101+
// disabled audio on previous scene
102+
activeScene.audioEnabled = false;
103+
}
91104
activeScene?.detachControl();
92105
engine.inputElement = canvas;
93106
scene.attachControl();
107+
// set listener to camera position of current scene
108+
if (Engine.audioEngine) {
109+
scene.audioEnabled = true;
110+
const listener = Engine.audioEngine.audioContext?.listener;
111+
if (listener) {
112+
const camPos = scene.activeCamera!.position;
113+
listener.setPosition(camPos.x, camPos.y, camPos.z);
114+
}
115+
}
94116
activeScene = scene;
95117
}
96118
};
@@ -128,7 +150,10 @@ export const Scene: React.FC<SceneProps> = ({ children, sceneOptions, onSceneRea
128150
})();
129151

130152
return () => {
131-
Reactylon.unmount(rootContainer.current!, disposeEngine);
153+
Reactylon.unmount(rootContainer.current!, () => {
154+
activeScene = null;
155+
disposeEngine();
156+
});
132157
rootContainer.current = null;
133158
};
134159
}, []);

0 commit comments

Comments
 (0)