Evoinsec
Evoinsec

Reputation: 43

A-Frame Play and pause a sound by clicking on the same element

I'm trying to make a sound play and pause by clickin the same element, I was able to play it but can't pause it and play it again every time I click, I'm Using javascript for this.

Here's what I have so far:

HTML

<a-image id="statue" src="#audio_logo" width="1.5" height="1.5" position="-27 7 -4" rotation="0 90 0" sound="src:#museumSound"> </a-image>

Javascript

  var sound = document.querySelector('#statue');
    sound.addEventListener('click', function () {
    sound.components.sound.playSound(); 
    });

Here I replicate the situation for better understanding, I what to be able to click the red square and play the sound and the click again on the same square and make it stop

https://codepen.io/EdgarJF/pen/jwdOZr

Upvotes: 0

Views: 1811

Answers (2)

Kk Mm
Kk Mm

Reputation: 57

thx ngokevin! you also saved me and your suggestion worked perfectly in my case.

Dear Evoinsec I can relate to you so much and have been lucky with ngokevin's help. so here I provide a part of my code.

Here is the HTML https://aframe.io/releases/0.3.0/aframe-inspector.min.js">

    <a-marker preset="hiro">

        <!--This is to Start/Pause audio-->
        <a-image id="audio"
                 src="./img/bird.jpg"
                 width="1" height="1"
                 position="1 0 0"
                 rotation="90 0 -90"
                 sound="src:./sound/bird.mp3"></a-image>
     </a-marker>


    <a-entity camera>
        <a-entity id="myCursor" 
                  cursor="fuse:true; maxDistance:30; timeout:500;" 
                  scale="0.03 0.03 0.03" 
                  position="0 0 -2" 
                  geometry="primitive: ring" 
                  material="color: red; shader: flat; opacity:0.5">
        </a-entity>
    </a-entity>
   </a-scene>
</body>

Here is the .js function init() { document.getElementById('audio').addEventListener('click', audioControle, false); }

function audioControle() { //SOUND STATUS
  var sound = document.querySelector('#audio');
  if (isPlaying == true) {
    // Do pause.
    sound.components.sound.pauseSound(); 
    isPlaying = false;
  } else if (isPlaying == false){
    // Do play.
    sound.components.sound.playSound(); 
    isPlaying = true;
  }
init();
}

This is maybe not the smartest way but worked for me. I hope this helps you.

Upvotes: 0

ngokevin
ngokevin

Reputation: 13233

Try pausing the sound.

document.querySelector('#museumSound').pause();

Or

sound.components.sound.pauseSound(); 

Keep a boolean to know whether to play or pause.

var isPlaying = false; 
if (isPlaying) {
  // Do pause.
  isPlaying = false;
} else {
  // Do play.
  isPlaying = true;
}

Upvotes: 1

Related Questions