Sound Test
1〜7のキーボードで鍵盤
// write as3 code here..
// 1〜7のキーボードで鍵盤
package {
import flash.display.Sprite;
import flash.filters.BlurFilter;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.SampleDataEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;
public class Main extends Sprite {
public const snd:Sound = new Sound();
public const wrapper:Sprite = new Sprite();
public const g:Sprite = new Sprite();
public const t:TextField = new TextField();
public const keys:Array = [0,2,4,5,7,9,11];
public const tones:Array = ["ド","レ","ミ","ファ","ソ","ラ","シ"];
public var ch:SoundChannel;
public var tone:Number = 1;
public function Main() {
//配置
addChild(wrapper);
wrapper.addChild(g);
wrapper.filters = [new BlurFilter(8,8,1)];
addChild(t);
//Text
t.selectable = false;
t.width = 300;
t.height = 300;
t.htmlText = "<P ALIGN='CENTER'><FONT SIZE='128'>!</FONT></P>";
t.x = (stage.stageWidth-t.width)/2;
t.y = (stage.stageHeight-t.textHeight)/2;
//描画
g.graphics.beginFill(0x660066);
g.graphics.drawRect(0,0,10,10);
g.graphics.endFill();
//音
snd.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
//キーボード
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
}
private function onKeyDown(e:KeyboardEvent):void {
var n:Number = e.keyCode - 48;
if ( n < 1 || n > keys.length ) return;
tone = (1+keys[n-1]/12)/2;
if ( ch ) ch.stop();
ch = snd.play();
t.htmlText = "<P ALIGN='CENTER'><FONT SIZE='128'>"+tones[n-1]+"</FONT></P>";
}
private function onKeyUp(e:KeyboardEvent):void {
var n:Number = e.keyCode - 48;
if ( n < 1 || n > keys.length ) return;
ch.stop();
t.htmlText = "<P ALIGN='CENTER'><FONT SIZE='128'>!</FONT></P>";
}
private function onSampleData(event:SampleDataEvent):void {
for (var c:int=0; c<8192; c++) {
var rad:Number = (Number(c+event.position)*tone/Math.PI);
var amp:Number = Math.sin(rad) / 4; // -1 から 1 の間の値なら OK
event.data.writeFloat(amp); // 左チャネルの音
event.data.writeFloat(amp); // 右チャネルの音
}
}
}
}