Peter Lum
Peter Lum

Reputation: 143

Play audio on marker detect A-frame AR.JS

I'm trying to play an audio source when a marker is detected with the A-frame and AR.JS libraries.

Currently I have the following scene, camera, and marker:

  <a-scene embedded arjs='sourceType: webcam; debugUIEnabled: false;';>
        <a-marker preset="hiro">
                <a-box position='0 0.5 0' material='color: black;'></a-box>
        </a-marker>
        <a-assets>
            <audio id="sound" src="audio.mp3" preload="auto"></audio>
        </a-assets>
    <a-entity sound="src: #sound" autoplay="false"></a-entity>
    <a-entity camera></a-entity>
    </a-scene>

I initially tried the following:

var entity = document.querySelector('[sound]');

      if(document.querySelector("a-marker").object3D.visible == true){
            entity.components.sound.playSound();
            console.log("playing");
        } else {
            entity.components.sound.pauseSound();
            console.log("not playing");
        }

However, it doesn't work. Any ideas as to why this isn't or doesn't work? I'm not even seeing a console log, so it doesn't appear to run either.

Upvotes: 3

Views: 3913

Answers (1)

jlvaquero
jlvaquero

Reputation: 8785

Did you register a component that handle the sound on every tick?

<a-scene embedded arjs='sourceType: webcam; debugUIEnabled: false;';>
       <a-assets>
            <audio id="sound" src="audio.mp3" preload="auto"></audio>
        </a-assets>
        <a-marker preset="hiro">
                <a-box position='0 0.5 0' material='color: black;' soundhandler> 
                </a-box>
        </a-marker>
        <a-entity sound="src: #sound" autoplay="false"></a-entity>
        <a-entity camera></a-entity>
</a-scene>

<script>
AFRAME.registerComponent('soundhandler', {
    tick: function () {
           var entity = document.querySelector('[sound]');
         if (document.querySelector('a-marker').object3D.visible == true) {
            entity.components.sound.playSound();
        } else {
            entity.components.sound.pauseSound();
        }

     }
});
</script>

Upvotes: 2

Related Questions