Monday, 26 August 2013

Remove unvanted clicks in generated sound in AS3

Remove unvanted clicks in generated sound in AS3

I am having the following problem when generating sound wave in Flash.
This is the generator part :
const SAMPLING_RATE:int = 44100;
const TWO_PI:Number = 2 * Math.PI;
const TWO_PI_OVER_SR:Number = TWO_PI / SAMPLING_RATE;
const SAMPLE_SIZE:int = 8192 / 4;
function generateSine(fq:Number):ByteArray
{
var bytes:ByteArray = new ByteArray();
var sample:Number;
var amp:Number = 1;
for (var i:int=0; i<SAMPLE_SIZE; i++)
{
sample = amp* Math.sin(i * TWO_PI_OVER_SR * fq );
bytes.writeFloat(sample);
}
bytes.position = 0;
return bytes;
}
and this is the playback part:
function playbackSampleHandler(event:SampleDataEvent):void
{
var sample:Number;
for (var i:int = 0; i < SAMPLE_SIZE && soundData.bytesAvailable; i++)
{
sample = soundData.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
function onClickPlay(e:MouseEvent)
{
soundData= new ByteArray();
soundData.writeBytes(generateSine(440),0,generateSine(440).length);
soundData.position = 0;
morphedSound.addEventListener(SampleDataEvent.SAMPLE_DATA,
playbackSampleHandler);
soundChannel = morphedSound.play();
}
Quick explanation: I basically write values for the sine function into the
ByteArray and than playback handler reads that array and plays back the
sound. I write only one 8192/4 sample buffer.
Problem: My problem is that when you do this there are annoying clicks on
the end of sound, which are the artifacts of sine wave being cut on a
value other than 0. So my question is how can I avoid this?
Bonus: I would also like to know how can I generate for example exactly
100 ms of sine wave when buffers in Flash are so strict i.e. from 2048 to
8192 ?
Links: If it helps my code is based on this tutorial
http://www.bit-101.com/blog/?p=2669 and my own explorations.

No comments:

Post a Comment