2013-02-08 39 views
1

我可以打一個蜂鳴聲是這樣的:如何在Actionscript中播放短音?

private var beep:Sound = new Sound(); 

private function beepInit():void { 
    var beepHandler:Function = new Function(); 

     beepHandler = function(event:SampleDataEvent):void { 
      for (var i:uint = 0; i < 2048; i++) { 
       var wavePos:Number = 20 * Math.PI * i/2048; 
       event.data.writeFloat(Math.sin(wavePos)); 
       event.data.writeFloat(Math.sin(wavePos)); 
      } 
     } 

     beep.addEventListener(SampleDataEvent.SAMPLE_DATA, beepHandler); 
} 

在應用程序啓動我打電話beepInit();

要播放,請調用:beep.play();

這是連續的聲音。我怎樣才能做到這一點? 500毫秒。短嗶?

回答

3

只要達到想要玩的時間,就需要停止創建樣本。您可以通過檢查創建的樣本數量與您想要播放的樣本數量來完成此操作。

要播放的採樣數量是採樣頻率(44100 /秒)乘以要播放的聲音的長度(以秒爲單位)。

private const sampleFrequency:uint = 44100; 
private var samplesCreated:uint = 0; 
private var lengthInSeconds:Number = 0.5; 
private var beep:Sound = new Sound(); 

private function beepInit():void { 
    var beepHandler:Function = function (event:SampleDataEvent):void { 
    for (var i:uint = 0; i < 2048; i++) { 
     if (samplesCreated >= sampleFrequency * lengthInSeconds) { 
     return; 
     } 
     var wavePos:Number = 20 * Math.PI * i/2048; 
     event.data.writeFloat(Math.sin(wavePos)); 
     event.data.writeFloat(Math.sin(wavePos)); 
     samplesCreated++; 
    } 
    }; 

    beep.addEventListener(SampleDataEvent.SAMPLE_DATA, beepHandler); 
}