Sound Tests
Click to Start
♥0 |
Line 64 |
Modified 2012-04-08 10:44:03 |
GPLv3 License
archived:2017-03-20 16:56:02
ActionScript3 source code
/**
* Copyright Abarrow ( http://wonderfl.net/user/Abarrow )
* GNU General Public License, v3 ( http://www.gnu.org/licenses/quick-guide-gplv3.html )
* Downloaded from: http://wonderfl.net/c/wIY5
*/
package {
import flash.display.Sprite;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.SampleDataEvent;
import flash.events.MouseEvent;
public class FlashTest extends Sprite {
public var sound:Sound;
public var channel:SoundChannel;
public var playing:Boolean;
public function FlashTest() {
// write as3 code here..
sound=new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA,sampleData);
stage.addEventListener(MouseEvent.CLICK, stopSound);
playing=false;
}
public function stopSound(event:MouseEvent):void{
if(playing){
channel.stop();
playing=false;
}else{
channel=sound.play();
playing=true;
}
}
public function sampleData(event:SampleDataEvent):void{
for(var c:int=0;c<8192;c++){
var pos:Number=Number(c+event.position);
var freq:Number=440;//A above middle C
var rate:Number=44100;
var volume:Number=0.5;
//base example
var value:Number=waveFunctionAt(0,pos*Math.PI*2*freq/rate)*volume;
/*
//beats example
//beats created between 440 Hz and 442 Hz
var value:Number=waveFunctionAt(0,pos*Math.PI*2*440/rate)*volume+
waveFunctionAt(0,pos*Math.PI*2*442/rate)*volume;
*/
/*
//harmonics example
//each successive harmonic one fifth of the previous volume
//using imperfect harmonics
var value:Number=0;
for(var overtones:int=0;overtones<20;overtones++){
value+=waveFunctionAt(0,pos*Math.PI*2*freq*Math.pow(2.01,overtones)/rate)*volume*Math.pow(0.2,overtones);
}
*/
var endValue:Number=(value+1)/2;
event.data.writeFloat(endValue);
event.data.writeFloat(endValue);
}
}
public function waveFunctionAt(func:int,pos:Number):Number{
var val:Number;
if(func==0){
//sine wave
return Math.sin(pos);
}else if(func==1){
//square wave
if(pos-Math.floor(pos/(2*Math.PI))*2*Math.PI<Math.PI){
return 1;
}else{
return -1;
}
}else if(func==2){
//triangle wave
val=pos-Math.floor(pos/(2*Math.PI))*2*Math.PI;
if(val<Math.PI){
return 1-Math.abs(val-Math.PI/2)/(Math.PI/2);
}else{
val-=Math.PI;
return -1+Math.abs(val-Math.PI/2)/(Math.PI/2);
}
}else if(func==3){
//saw wave
val=pos-Math.floor(pos/(2*Math.PI))*2*Math.PI;
return -1+val/Math.PI;
}else{
return 0;
}
}
}
}