Share Pastebin
Guest
Public paste!

Flex Tone Generator Helper Class

By: a guest | Jun 9th, 2010 | Syntax: ActionScript 3 | Size: 1.29 KB | Hits: 317 | Expires: Never
Copy text to clipboard
  1. package {
  2.         import flash.events.SampleDataEvent;
  3.         import flash.media.Sound;
  4.        
  5.         public class ToneGenerator {
  6.                
  7.                 [Bindable]
  8.                 public var amp_multiplier_right:Number = 0.15;
  9.                 [Bindable]
  10.                 public var amp_multiplier_left:Number = 0.15;
  11.                 [Bindable]
  12.                 public var freq_right:Number = 350;
  13.                 [Bindable]
  14.                 public var freq_left:Number = 350;
  15.                
  16.                 public static const SAMPLING_RATE:int = 44100;
  17.                 public static const TWO_PI:Number = 2*Math.PI;
  18.                 public static const TWO_PI_OVER_SR:Number = TWO_PI/SAMPLING_RATE;
  19.                
  20.                 public var tone:Sound;
  21.                
  22.                 public function ToneGenerator() {
  23.                 }
  24.                
  25.                 public function stopTone():void {
  26.                        
  27.                         tone.removeEventListener(SampleDataEvent.SAMPLE_DATA, generateSineTone);
  28.  
  29.                 }
  30.                
  31.                 public function startTone():void {
  32.                                
  33.                         tone = new Sound();
  34.                        
  35.                         tone.addEventListener(SampleDataEvent.SAMPLE_DATA, generateSineTone);
  36.                        
  37.                         tone.play();
  38.                        
  39.                 }
  40.                
  41.                 public function generateSineTone(e:SampleDataEvent):void {
  42.                        
  43.                         var sample:Number;
  44.                        
  45.                         for(var i:int=0;i<8192;i++) {
  46.                                 sample = Math.sin((i+e.position) * TWO_PI_OVER_SR * freq_left);
  47.                                 e.data.writeFloat(sample * amp_multiplier_left);
  48.                                 sample = Math.sin((i+e.position) * TWO_PI_OVER_SR * freq_right);
  49.                                 e.data.writeFloat(sample * amp_multiplier_right);
  50.                         }  
  51.                        
  52.                 }
  53.                
  54.  
  55.         }
  56. }