How to determine the end of audio playback?

I change the position of the sound every time a new position comes from the server, but I absolutely do not understand how to determine that the sound is completely ended

isPlaying - always returns true even when I don’t hear sound

Audio#onEnded – three.js docs (threejs.org)

I can’t find any example usage, but it’s probably used like this

const sound = new THREE.Audio( listener );

// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  sound.setBuffer( buffer );
  sound.onEnded = () => {
    console.log("onEnded")
    sound.isPlaying = false
  }
  sound.play()
});
1 Like

This only works after calling .stop()

is your audio looping?

No
brickSound.setLoop(false)

You can check, there is no way to determine the end of the sound

I’m not in an environment where I can code right now. But if I couldn’t figure it out, I’d use JavaScripts setTimeout() function.

If my bricksound was 1 second long, then after I started to play it, I’d also set a timeout.

const myTimeout = setTimeout(()=>{console.log("brick sound finished")}, 1000);

I got it to work.
I added a button to my html,
<button id="button">Play Audio</button>

My JavaScript

import * as THREE from 'three'

new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100)
camera.position.z = 2

// create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add(listener);

// create a global audio source
const sound = new THREE.Audio(listener);

// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load('sounds/ambient.ogg', function (buffer) {
    sound.setBuffer(buffer);
    sound.onEnded = () => {
        console.log("onEnded")
        sound.isPlaying = false
    }
});

document.getElementById("button").addEventListener("click", () => {
    sound.play()
})
2 Likes

I see I have used

sound.source.onended=function()[ …

event in my code.I think I got that from here: Migrating from webkitAudioContext - Web APIs | MDN (mozilla.org)

1 Like