I can't understand why the audio file won't play in the LoadingManager callback function. It's completely illogical to me. I hope somebody can explain it to me. I stripped my code to only load a single mp3 file and play it after loading is complete.
In the console I get this error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'play')
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>Test</title>
<script type="importmap">
{
"imports": {
"three": "../threejs/build/three.module.js"
}
}
</script>
<script type="module" src="main2.js"></script>
</head>
<body>
<style>
body {
margin: 0;
}
</style>
<div id="overlay">
<button id="startButton">Play</button>
</div>
</body>
</html>
main2.js:
import * as THREE from 'three';
let camera, scene, renderer, sndMusic1;
// SCENE
scene = new THREE.Scene();
// CAMERA
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1500 );
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true, alpha: false } );
document.body.appendChild(renderer.domElement);
const manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
const audioLoader = new THREE.AudioLoader(manager);
const startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', init );
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onLoad = function () { // LoadingManager callback function
console.log('All files loaded.');
sndMusic1.play();
}
function init() {
const overlay = document.getElementById( 'overlay' );
overlay.style.display = "none"; // Hide the start button
const listener = new THREE.AudioListener();
camera.add( listener );
audioLoader.load( './sound/arise5.mp3', function( buffer ) {
sndMusic1 = new THREE.Audio( listener );
sndMusic1.setBuffer( buffer );
});
}