bpm tap
...
@author 9re
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.ui.Keyboard;
import flash.utils.getTimer;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
/**
* ...
* @author 9re
*/
public class BpmTap extends Sprite
{
private var _result:TextField;
private var _times:Array;
private var _timer:uint;
public function BpmTap()
{
var buttonStyle:Object = {
fontFamily: "Helvetica, Arial",
fontSize: 18,
textAlign: "center",
color:"#ffffff"
};
var resultStyle:Object = {
fontFamily: "Helvetica, Arial",
fontSize: 12,
textAlign: "center"
};
var countStyle:Object = {
color: "#0000ff"
}
var css:StyleSheet = new StyleSheet();
css.setStyle(".button", buttonStyle);
css.setStyle(".result", resultStyle);
// label of the button
var label:TextField = new TextField();
label.width = 60;
label.height = 25;
label.styleSheet = css;
label.x = -label.width / 2;
label.y = -label.height / 2;
label.htmlText = "<span class='button'>TAP</span>";
label.selectable = false;
addChild(label);
// button
var sp:Sprite = new Sprite();
sp.graphics.beginFill(0);
sp.graphics.drawCircle(0, 0, 40);
sp.graphics.endFill();
sp.x = stage.stageWidth / 2;
sp.y = stage.stageHeight / 2;
addChild(sp);
sp.addChild(label);
sp.buttonMode = true;
sp.tabEnabled = false;
// result window
_result = new TextField();
_result.styleSheet = css;
_result.width = stage.stageWidth;
_result.y = 100;
addChild(_result);
_times = [];
clearArray();
// catch click
sp.addEventListener(MouseEvent.CLICK, clickHandler);
// catch keydown
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
}
private function keyDownHandler(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.ENTER)
countBPM();
}
private function clickHandler(e:MouseEvent):void
{
countBPM();
}
private function countBPM():void
{
_times.push(getTimer());
if (_times.length > 10)
_times.shift();
if (_times.length < 2)
return;
var bpm:Number = 60000 / (_times[_times.length - 1] - _times[0]) * _times.length;
bpm = Math.floor(bpm * 100) / 100;
_result.htmlText = "<span class='result'>BPM: <span class='count'>" + bpm.toString() + "</span></span>";
clearTimeout(_timer);
_timer = setTimeout(clearArray, 5000);
}
private function clearArray():void
{
_times.length = 0;
_result.htmlText = "<span class='result'>BPM:</span>";
}
}
}