我正在使用Flex + AS3編寫簡單的節拍器組件。例如,我希望它在每個500毫秒後播放'tick1'聲音,並且每第4次播放另一個聲音'tick2'。但實際上聲音之間的延遲並不等同 - 有時候會更小,有時會更大一些。我在最新的Chrome上測試它。聲音播放延遲錯誤
這裏我的代碼:
//Somewhere here button bound to the 'toggle' function
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.media.SoundTransform;
import flash.media.SoundChannel;
private var bpm:Number = 120; //2 bit per second, delay=500ms
private var period:Number = 4;
private var timer:Timer = new Timer(bpm, period);
[Embed(source='sounds/1.mp3')]
private var tickSound1Class:Class;
private var tickSound1:Sound;
[Embed(source='sounds/2.mp3')]
private var tickSound2Class:Class;
private var tickSound2:Sound;
private var trans:SoundTransform = new SoundTransform(1);
private function init():void {
....
tickSound1 = new tickSound1Class() as Sound;
tickSound2 = new tickSound2Class() as Sound;
update();
timer.addEventListener(TimerEvent.TIMER, onTimerEvent);
....
}
private function update():void {
timer.delay = 1000 * 60/bpm;
timer.repeatCount = 0;
}
private function toggle():void {
if (timer.running) {
timer.reset();
startStopButton.label = "Start";
} else {
update();
timer.start();
startStopButton.label = "Stop";
}
}
private function onTimerEvent(event:TimerEvent):void {
var t:Timer = event.currentTarget as Timer;
if (t.currentCount % period == 0)
tickSound1.play(0, 0, trans);
else
tickSound2.play(0, 0, trans);
}
謝謝。我決定使用第二種方法。研究如何抽樣和取樣聲音有一段時間,但它似乎是最好的解決方案,因爲我不想使用服務器端預生成聲音。 – 2013-02-10 12:07:26
不客氣:)請注意,有2048個樣本(大約50毫秒)和8192個樣本(大約50毫秒)的上限和下限。190 ms),您可以在單個SAMPLE_DATA事件中傳遞,因此,在某些情況下,您需要使用滴答聲並在連續幾次事件中寫入。 – skozin 2013-02-10 18:33:22
原因是可能發生的情況是當前event.position比下一次tick更早,但(event.position + 2048)更晚。您將寫入A =(tickTime * 44.1 - event.position)沉默樣本,然後B =(2048 - A)從開始的滴答聲音樣本。然後,在下一個採樣數據事件中,C =(tickSound.length * 44.1-B)從不是第B'個樣本開始的滴答聲樣本,以及再次D =(2048-C)沉默樣本沉默= 2零漂)。 – skozin 2013-02-10 18:34:00