Search code examples
aframe

Is there an easy way to get the duration of a a-frame sound?


I use A-frame and wish to play an animation for the duration of a sound (using the sound component). However I am unable to get this value. Is there an easy way to discover the length of an *.mp3 file? (Which currently is saved as a url-string) Or will I have to use external libraries?

<a-entity sound:src="http://<website>.audioFile.mp3"></a-entity>

Solution

  • To get this from the sound component attached to the element you can write

    var mySound = document.querySelector('#yourElement').components.sound.attrValue.src
    

    then

    var myAudioDuration = document.querySelector(mySound).duration
    

    And the duration will be stored in that variable.


    Alternatively, assuming your audio file is saved in assets with an id of 'myAudio' e.g.

    <a-assets>
     <audio id="myAudio" src="path/to/audiofile.mp3"></audio>
    </a-assets>
    

    You can write

    var myAudioDuration = document.querySelector('#myAudio').duration
    

    And the duration will be stored in that variable.

    I hope that helps

    You can read more about audio/video tag controls here