Skip to main content
NefJack
Participating Frequently
June 14, 2022
Question

Event listener to detect when sound complete for HTML5 document

  • June 14, 2022
  • 1 reply
  • 346 views

Hi,

I've tried looking around for info on this, but I haven't had much luck. 

Is there an event listener to detect when a sound has completed playing?

 

To give some context to what I am trying to do.

I'm trying to play a visualizer animation that plays while a sound is playing. But I want the animation to stop when the sound file has completed playing.

 

Thanks in advance!

 

    This topic has been closed for replies.

    1 reply

    NefJack
    NefJackAuthor
    Participating Frequently
    June 14, 2022

    Nevermind, I came across something that seems to be working for me.

    Here's what I did, in case anyone else is looking for something similar:

     

    _this.play_btn.on('click', function(){
    	if (_this.bgm)
    	_this.bgm.play();
    	else
    		_this.bgm = createjs.Sound.play("soundfile");
    		_this.bgm.addEventListener("complete",stopvis.bind(this));
    			function stopvis(){
    			_this.visualizer.visible = false;
    			}
    });

     

    Legend
    June 14, 2022

    If that can execute multiple times, it's going to keep adding more and more event listeners. You have to remove the event listener after it's done its job 

    NefJack
    NefJackAuthor
    Participating Frequently
    June 14, 2022

    Thanks for the heads up @ClayUUID 

     

    Will this do the trick?

     

    _this.play_btn.on('click', function(){
    	if (_this.bgm)
    	_this.bgm.play();
    	else
    		_this.bgm = createjs.Sound.play("soundfile");
    		_this.bgm.addEventListener("complete",stopvis.bind(this));
    			function stopvis(){
    			_this.visualizer.visible = false;
    			}
                    _this.bgm.removeEventListener("complete",stopvis.bind(this));
    
    });