Hagsten / Talkify

Javascript Text to speech library
216 stars 32 forks source link

isPlaying with TtsPlayer() #38

Closed Uup115 closed 5 years ago

Uup115 commented 5 years ago

Hello again...

Really enjoying the API. Very useful it is. Thanks!

I'm attempting to use the "isPlaying" method like this:

player.playText('Finding your location. This can take a couple of minutes.'); while (player.isPlaying()) { do something... }

Code inside the while loop never executes. Am I not using the method properly?

Best Regards

Hagsten commented 5 years ago

Hi!

The metod playText is async - it will complete before the audio is loaded. Hence when you hit the following while loop the player has not yet started playing so it will skip it.

We have an event model that allows you to know when audio is loaded/playing/etc. We also have a new event model not yet documented, i will give an example when i get the time.

Hope it helps :)

Uup115 commented 5 years ago

Hello,

Per your suggestion... The event, "onPlay", successfully fires at the start of audio playback and does something inside the while loop.

player.subscribeTo({ onPlay: function(){ while (player.isPlaying()) { do something... } do something else... } });

However, when the audio playback finishes, something else never happens. It seems to be forever inside the while loop. Does the "isPlaying" method become false, when audio playback finishes?

Best Regards

Hagsten commented 5 years ago

Hey,

I would actually not recommend that you use the isPlaying method in the way you are. What are you planning to do inside that while loop? That loop will iterate quite alot :).

IsPlaying is intended to be called when you want to get the current status rather than polling it. I would instead recommend you to use our events and stop using while loops. It is hard to help without knowing what you plan to do inside the loop, for most use cases you would do something when audio starts playing (i.e. set some state) and then do something else when audio stops (i.e. reset some states). Have a look at my two fiddles below, the first one hooks into our messageBus (not yet documented) and the other one into our older, documented, events.

http://jsfiddle.net/andreas_hagsten/x6pve0jd/8/ http://jsfiddle.net/andreas_hagsten/wnzqkd32/3/

Uup115 commented 5 years ago

Hello,

Both "onPause" and "messageBus" work nicely. Thanks for the insight.

My thought was to poll "isPlaying" every 300 msec or so, using setTimeout() inside the while loop. I didn't realize the "onPause" event also fires when audio playback finishes. Thanks for the clarification.

Best Regards

Hagsten commented 5 years ago

No worries! Glad I can help.

I will make sure to update the docs regarding the messagebus/subscribe pattern.