AS3 BeatMachine – Timer Inaccuracy
I've always thought about experimenting with flash in the realm of audio. Lucky me, I finally got a chance! Before discovering the fun in programming (nerd!) I use to spend a lot of my time creating digital music... Music and maths have always being passionate things for me. So, with this being said, you can understand how I could think of a lot of audio related flash web applications. I say "could" because after this experiment, I'm not sure how capable Flash is of doing such things.
The experiment consists of a very simple step sequencer, or a drum machine. You can download the source if you want to have a look at it. It is a very simple API that can load tracks into a sequencer. You can then load a sound on each track and place notes in specific locations of the compass, so that when you press play, a rhythm starts playing. I planned on doing a user interface for it, but I desisted given the bad results I got.
As you can hear in the demo, the player doesn't seem to be able to keep a good tempo. The reason for this is that the sequencer needs a clock to trigger beats in a given BPM (beats per minute) and the flash player can't do this with enough accuracy. Both enterframe based timers and the Timer class itself are very imprecise when dealing with small intervals of time such as 60ms (around 120bpm). The timer executes at values like 70ms, 55ms, 87ms, 120ms, 293ms, etc. Even though the Clock class in the BeatMachine API tries to compensate for these failures, it is not enough to keep a precise tempo. I also made an effort in not using events, so that the garbage collector doesn't mess with the rhythm when it comes around, but again, the results are insatisfactory.
One big TO-DO with this would be to test it in fp10. Apparently the updated player handles sound in a different thread, so that would be a big help. Anyway, this is still discouraging because even though sound routines could be set aside so that the timers trigger sooner to when they are supposed to, heavy visual activity could also slow down the timers. I think the only solution would be to send the timers to a different thread too.
I hope I'm wrong, so if anybody would like to have a look at the source and post any suggestions, be my guest! If the problems could be overcomed, then it would be nice to enhance the API so that it supports more features and perhaps even adapt it so it can easily be connected to some graphics UI.
Any ideas?
[UPDATE] See comments below for additional info on the subject.