How to make a Timer accurate? (Flash / ActionScrip

2019-05-11 02:45发布

问题:

I'm using the following method to dispatch a sound in X times/minute (X is determined through bpm, which is a NumericStepper object)

var mainTimer:Timer = new Timer(60 / (bpm.value * 1000),0);
mainTimer.addEventListener(TimerEvent.TIMER, fl_TimerHandler,false, 0, true); 
mainTimer.start();

function fl_TimerHandler(event:TimerEvent):void
     {
        metroTransform.volume = vol;
        flash.media.SoundMixer.soundTransform = metroTransform;
        metroChannel = metro.play();
        mainTimer.delay = 60 / bpm.value * 1000;
      }

According to this http://www.metronomeonline.com/ the sound is not sitting well. Is there something I can do to fix this problem I'm stuck in?

Path to the output file I'm getting: http://conatur.net/metroBig.swf

回答1:

http://cookbooks.adobe.com/post_Accurate_timer-17332.html might help you.

Problem
The delay between 2 events of the timer class depends on many factors ( fps, memory, played movie clip end i.e. ). The timeout set to property delay of timer class is only approximate so there needs to be a way to increase the accuracy of the timer.

Solution
My solution to increase the accuracy is to extend the timer class and force the timer to make more cycles depending of the custom property accurate. In this way the delay between 2 events of the timer will be set delay - + accurate /2. Because the rising of the event depends form many factors truly delay between 2 events is from: delay - accurate/2 to next fired event from flash player.



回答2:

Hum shouldn't the delay value be

60000 / bpm.value
// with BPM = 80 we have 60000/80 = 750

instead of

60 / (bpm.value * 1000)
// with BPM = 80 we have 60/80000 = 0.00075

And as the Time delay values is described in the documentation:

delay:Number — The delay between timer events, in milliseconds. A delay lower than 20 milliseconds is not recommended. Timer frequency is limited to 60 frames per second, meaning a delay lower than 16.6 milliseconds causes runtime problems.

I guess 750 milliseconds would fit be better than 0.00075 milliseconds.

Though, when I test your SWF and set the BPM at 60, it sounds every second without problem so I guess the bpm.value is not what it looks like.


Anyhow, when I open your swf and the "metronomeonline" website on two tabs (or windows) and set them at the same BPM, they sound synchronized to me.