- AS3 playback of sound byte array doesn't begin at the start
- var soundBA:ByteArray = new ByteArray();
- var sound:Sound = new Sound();
- var ch:SoundChannel = new SoundChannel();
- var recordingsArray:Array = new Array();
- soundBA.clear();
- soundBA.length = 0;
- //I collect the recorded byteArray within an array
- soundBA.writeBytes(recordingsArray[0]);
- soundBA.position = 0;
- trace("Start POS "+soundBA.position); //traces 0
- sound.addEventListener(SampleDataEvent.SAMPLE_DATA, sound_sampleDataHandler, false, 0, true);
- ch=sound.play();
- this.addEventListener(Event.ENTER_FRAME, updateSeek, false, 0, true);
- public function updateSeek(event:Event):void {
- trace("current Pos "+soundBA.position); //the first trace event is "current Pos 163840"
- }
- function sound_sampleDataHandler(event:SampleDataEvent):void {
- for (var i:int = 0; i < 8192; i++)
- {
- if (soundBA.bytesAvailable < 4)
- {
- break;
- }
- var sample:Number = soundBA.readFloat();
- event.data.writeFloat(sample);
- event.data.writeFloat(sample);
- }
- }
- public function updateSeek(event:Event):void {
- trace("current pos in ms: " + ch.position);
- trace("current pos in bytes: " + (ch.position * 44.1 * 4 * 2));
- trace("current pos in %: " + (100 * ch.position / sound.length));
- }
- package
- {
- import flash.display.Sprite;
- import flash.events.Event;
- import flash.events.SampleDataEvent;
- import flash.media.Sound;
- import flash.media.SoundChannel;
- import flash.net.URLRequest;
- import flash.utils.ByteArray;
- public class SoundTest extends Sprite
- {
- private var soundSrc:Sound;
- private var soundPlayer:Sound;
- private var soundData:ByteArray;
- private var soundChannel:SoundChannel;
- public function SoundTest()
- {
- soundSrc = new Sound();
- soundSrc.addEventListener(Event.COMPLETE, startPlayback);
- soundSrc.load(new URLRequest("sound.mp3"));
- }
- private function startPlayback(e:Event = null):void
- {
- soundData = new ByteArray();
- soundSrc.extract(soundData, soundSrc.length * 44.1, 0);
- soundData.position = 0;
- soundPlayer = new Sound();
- soundPlayer.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
- soundChannel = soundPlayer.play();
- addEventListener(Event.ENTER_FRAME, updateTime);
- }
- private function onSampleData(e:SampleDataEvent):void
- {
- for (var i:int = 0; i < 8192; i++)
- {
- if (soundData.bytesAvailable < 4)
- {
- break;
- }
- var sampleL:Number = soundData.readFloat();
- var sampleR:Number = soundData.readFloat();
- e.data.writeFloat(sampleL);
- e.data.writeFloat(sampleR);
- }
- }
- private function updateTime(e:Event):void
- {
- trace("current pos in ms: " + soundChannel.position);
- trace("current pos in bytes: " + (soundChannel.position * 44.1 * 4 * 2));
- trace("current pos in % (method 1): " + (100 * soundChannel.position / soundSrc.length));
- // it also works
- trace("current pos in % (method 2): " + (100 * soundChannel.position / (soundData.length / (44.1 * 4 * 2))));
- }
- }
- }