2

I'm having a hard time on how to play a sound in the game I'm currently developing.

I need to play sound after an animation but when I tried to call sound.play().

And the browser state that you can only play a sound using human gestures?

Anyone have some tricks kindly share in here. Thanks.

ADDED ============

I'm having this issue in mobile devices.

POGI
  • 335
  • 1
  • 3
  • 12
  • You'll have to post some code, generally playing a sound is quite trivial, you just use an audio tag or `new Audio` – adeneo Oct 29 '16 at 13:51

2 Answers2

6

Sample of your code will be helpful, but this question is tagged jQuery so I assume you are looking for solution for this library. And jQuery.animate takes callback and runs it after animation is done, look:

$( "#element").animate({
    opacity: 0.25
  }, 5000, function() {
    // animation is complete
    // play your sound here
});

You can find more examples in documentation.

Remek Ambroziak
  • 790
  • 8
  • 11
  • at those comments, inside the callback, I recommend Howler.js https://github.com/goldfire/howler.js/ Audio library, for working with animations. – George Oct 30 '16 at 18:13
  • Hi I appreciated your answer but this code won't work on mobile as the browser stated that you can only play a sound using human gestures. – POGI Nov 01 '16 at 09:04
4

@Remek's answer is right if you are using jQuery to animate, but you also tagged TweenJS, so you can use call, which queues a function call in a TweenJS queue.

createjs.Tween.get(obj)
    .to({x:1000}, 3000, createjs.Ease.quadOut)
    .call(function(tween) {
        createjs.Sound.play("soundId");
    });

You can use a call within a Tween queue, or at the end. Note that tweens also dispatch events, but only have a "change" event, and not a "complete" event because tweens can be looped, reversed, and constantly chained to add additional animations, so they don't really "complete". This is why the call method exists.

The call method also accepts parameters and a function scope. http://www.createjs.com/docs/tweenjs/classes/Tween.html#method_call


Regarding your question about "human gestures", this applies mostly to mobile platforms, where you must click something to play a sound (which unlocks the audio context, so it just has to happen once). The latest SoundJS automatically handles that for you, automatically playing an empty sound when you press (even for a scroll). Note that using scrolls to do this has been deprecated, so the user may have to "click/tap" something to make this work properly - but SoundJS will handle unlocking for you in this case.

Cheers.

Lanny
  • 11,244
  • 1
  • 22
  • 30
  • Hi thanks for your answer, have you tried this to run on mobile devices? I tried it but i'm still have an issue of "you can only play a sound using human gestures" – POGI Nov 01 '16 at 09:06
  • See the section I added above -- you need to have a physical tap on devices to unlock the audio context. – Lanny Nov 01 '16 at 15:11