문제

I can play a beep sound like this:

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);
}

At application start I call beepInit();

To play, call: beep.play();

This is continuous sound. How can I make it to ex. 500 ms. short beep?

도움이 되었습니까?

해결책

You need to stop creating samples as soon as you reach the length you want to play. You can do this by checking the amount of samples created against the amount of samples you want to play.

The amount of samples you want to play is the sample frequency (44100/second) multiplied by the length of the sound you want to play (in seconds).

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 );
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top