-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathALF.as
1482 lines (1106 loc) · 49.7 KB
/
ALF.as
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2009 Music and Entertainment Technology Laboratory - Drexel University
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package{
import flash.utils.ByteArray;
import flash.events.SampleDataEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.*;
import flash.events.Event;
import flash.utils.Endian;
import flash.events.IOErrorEvent;
import flash.events.EventDispatcher;
import flash.utils.*;
import DATF;
/*
Class: ALF.as
The Audio processing Library for Flash. ALF plays an audio file (MP3 or wav) using the dynamic audio functionality
of Actionscript3 and provides methods for obtaining audio features and manipulating the audio output stream on a frame by frame basis.
*/
public class ALF extends EventDispatcher{
// Sound playback
private var audio:Sound;
private var mp3Audio:Sound;
private var audioCh:SoundChannel;
private var mp3Bytes:ByteArray;
private var playBytes:ByteArray;
private var loadedData:URLLoader;
public var numCh:uint;
public var fs:uint;
public var trackName:String;
private var leftSample:Number;
private var rightSample:Number;
private var mp3Position:uint = 0;
private var wavPosition:uint;
private var fileExt:String;
private var waveLoader:URLLoader;
private var mp3Loader:URLLoader;
private var STEREO:Boolean = false;
private var READY:Boolean = false;
public var STOP:Boolean = false; //made this public so the calling script can figure out if audio is playing
private var CONTINUE:Boolean = false;
// variables needed for determining the duration and position in audio
public var duration:Number;
public var bytesPerSample:int;
public var startTime:uint; // user specified playback position of the track (in msec)
public var ITER:uint= 0;
public var LOAD_COUNT:uint = 0;
// Framing
public var chVal:Number;
public var numSamplesToPlay:Number;
private var userFrameRate:uint = 0;
public var frameSize:uint = 4096;
public var hopSize:uint = 2048;
private var LOOK_AHEAD:Boolean = false;
private var frameLookAhead:Number;
// DATF
private var DSP:DATF;
//C Memory stuff
private var cRAM:ByteArray;
private var audioPtrs:Array;
private const sizeofFloat:Number = 4;
//Buffer Status vars
private var leftBufferStatus:Array;
private var rightBufferStatus:Array;
private var numSamplesLeft:int;
private var numSamplesRight:int;
// Events
public const NEW_FRAME:String = "newFrame";
public const FILE_LOADED:String = "audioFileLoaded";
public const FILE_COMPLETE:String = "audioFileCompleted";
public const PROG_EVENT:String = "newProgressEvent";
public const URL_ERROR:String = "urlErrorEvent";
// Utility
private var i:uint;
private var tempInt:int;
private var tempNum:Number;
private var verbose:Boolean;
public var loadProgress:Number; // publicly available so audio file-loading can be monitored from outside of the class
private var INITIALIZED:Boolean = false;
// Features
public var inten:Number, cent:Number, band:Number, roll:Number, flux:Number, pitchVal:Number;
public var harmAmps:Array, harmFreqs:Array, magArr:Array, fftArr:Array, lpcArray:Array, freqResp:Array;
/*
Topic: Usage
ALF is a library whose functions return audio features and perform other operations on an audio file on a frame-by-frame basis.
In this current version, an event, NEW_FRAME, is dispatched whenever a new audio frame begins. To synchronize
visual events with audio, use NEW_FRAME as you might use onEnterFrame (AS event that signals a new frame in the
timeline).
We recommend using the event NEW_FRAME rather than onEnterFrame since these events are not guaranteed to be synchronized. Applications
can still use onEnterFrame, but the calls to ALF should be done using the NEW_FRAME event. In this case, unique values may not be
returned every frame since the onEnterFrame runs in parallel with the NEW_FRAME callback and has no dependency.
A simple example that plays a file and plots a feature is shown below:
Topic: Example
This is a simple example that loads an audio file into ALF and then plots one of the audio features as the song plays with a
look-ahead of 20 frames. For visual applications the frame look-ahead is implemented so that the developer has some foreknowledge
of events before they happen (i.e. large changes can be transitioned smoothly).
The values are calculated in real time and then displayed on the stage. On each frame, a line segment is drawn from the feature
value of the previous frame to the feature value of the current frame.
(start code)
package{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Graphics;
import flash.geom.ColorTransform;
public class ALFDemo extends MovieClip{
private var myALF:ALF;
private var intensity:Number;
// Display
var vidFrame:uint = 0;
var line:MovieClip;
var line2:MovieClip;
var colorChange:ColorTransform;
var lineArr:Array;
var xCoord:uint = 0;
var val:Number;
// Utilities
var i:uint = 0;
var count:uint = 0;
var frameCount:uint = 1;
var alfCount:Number = 1;
var offset:uint = 2;
public function ALFDemo(){
// Define audio file, use this example file or specify the path (local or server) of your own file
var str:String;
str = 'http://music.ece.drexel.edu/~jscott/speech_dft.mp3';
// Create ALF object
myALF = new ALF(str, 0, 30, false, 20); // 30 fps with 20 frame look-ahead
myALF.addEventListener(myALF.NEW_FRAME, onFrame); // Audio callback (ALF functions should be called in this handler)
myALF.addEventListener(myALF.FILE_LOADED, audioLoaded); // Adds listener for when the audio data has loaded
myALF.addEventListener(myALF.FILE_COMPLETE, audioFinished); // Event for when the file has fiished playing
// Initialize objects for drawing
lineArr = new Array();
line = new MovieClip();
lineArr.push(line);
line.graphics.lineStyle( 1, 0xFF0000, 1000);
line.graphics.moveTo(0, 400);
addChild(line);
}
// This handles the event that ALF dispatches for each audio frame. If your video frame rate is
// the same, you should have synchronicity between your audio feature values and your video frames,
// that is, there should be no lag or offset between the value calculated and the audio that is playing.
public function onFrame(event:Event):void{
intensity = myALF.getIntensity();
// Clear screen if reached border
if(xCoord > 550){
for(i = 0; i < lineArr.length; i++){
lineArr[i].graphics.clear();
}
line.graphics.moveTo(offset, 400);
xCoord = 0;
}
if(frameCount > offset){
// Draw line
val = intensity/10
if(isNaN(val)){ val = 0;}
line.graphics.lineStyle( 1, 0xFF0000, 1000);
line.graphics.lineTo(xCoord, 400 - val);
addChild(line);
// Set up for draw on next frame
line = new MovieClip();
lineArr.push(line);
line.graphics.moveTo(xCoord, 400 - val);
}
frameCount++;
xCoord = xCoord + 3;
}
// This funciton is called when the audio has been loaded in ALF and the FILE_LOADED event has been dispatched
public function audioLoaded(event:Event):void{
myALF.startAudio();
trace('playing audio ...');
}
// This funciton is called when the audio has finished playing and the FILE_COMPLETE event has been dispatched
public function audioFinished(event:Event):void{
trace('audioFinished');
trace('---------------------------------------');
}
}
}
(end)
*/
/*
Group: Constructor
Constructor: ALF
Constructor for ALF.
Parameters:
filename - The filename of the audio file to play. This must be a .wav or .mp3 file.
_startTime - An Int the range (0 - duration) specifying where playback should begin in the audio file. Start
time is represented in milliseconds (1msec = 0.001 seconds)
framesPerSecond - The frame rate in frames per second. Values between 10 and 40 fps are currently supported.
_verbose - When true, prints the .wav file header in the output window. The header contains information such as the
sample rate, bit rate, number of channels, size, etc. This parameter does not effect mp3 files.
Notes:
The frame rate that audio is processed at is based on the NEW_FRAME (<ALF Events>) event. Make sure to set the frame
rate of your .fla file to the same rate you enter as the framesPerSecond parameter if you want good synchronization
between audio and video.
Currently ALF does not have a default destructor method to free the associated memory when you're done with it. Rather,
ALF's should be re-used. This can be accomplished simply by calling the loadNewSong method and passing the
appropriate string for the new audio file as an argument.
*/
public function ALF(filename:String, _startTime:uint, framesPerSecond:uint, _verbose:Boolean, _frameLookAhead:Number){
if(frameLookAhead > 0) LOOK_AHEAD = true;
// Save parameter values
verbose = _verbose;
frameLookAhead = _frameLookAhead;
startTime = _startTime;
//parse off the track name so we can save that as an ALF property
trackName = filename;
var res:Array = trackName.split('/');
trackName = res[res.length - 1];
// FrameSize is set after the sound file has been loaded in
userFrameRate = framesPerSecond;
trace('fps = '+userFrameRate);
// Initialize the sound objects
audio = new Sound();
audioCh = new SoundChannel();
// Find file extension
fileExt = filename.substr(filename.length - 3, 4);
fileExt = fileExt.toLowerCase();
switch(fileExt){
case "wav": // Initialize wav objects
waveLoader = new URLLoader(); // Initialize URL Looader
waveLoader.dataFormat = URLLoaderDataFormat.BINARY; // Set to binary format
waveLoader.addEventListener(Event.COMPLETE, waveLoaded); // Event for when file is loaded
waveLoader.addEventListener(ProgressEvent.PROGRESS, waveProgress); // Event for getting file loading data
waveLoader.addEventListener(IOErrorEvent.IO_ERROR, waveLoadError); // Event for file loading erros
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, wavAudioCallback); // Add event for each audio frame
var waveRequest:URLRequest = new URLRequest(filename); // Set filename to load
// Attempting to read in the wave file
waveLoader.load(waveRequest);
break;
case "mp3": // Initialize mp3 objects
var mp3Request:URLRequest = new URLRequest(filename); // Load filename
mp3Bytes = new ByteArray(); // For raw samples from file
mp3Bytes.endian = Endian.LITTLE_ENDIAN; // Set endianess for data processed in CPP
playBytes = new ByteArray(); // For playback of endian converted samples
playBytes.endian = Endian.BIG_ENDIAN; // Set endianess for playback in Flash
mp3Audio = new Sound(); // Sound object for audio file
STEREO = true;
fs = 44100;
// Attempting to read in the MP3 file
mp3Audio.addEventListener(IOErrorEvent.IO_ERROR, mp3LoadError); // Handle failed load
mp3Audio.addEventListener(Event.COMPLETE, mp3Loaded); // Dispatched when file is loaded
mp3Audio.addEventListener(ProgressEvent.PROGRESS, mp3Progress);
mp3Audio.load(mp3Request);
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, mp3AudioCallback); // Dispatched on each audio frame
break;
default: trace('Invalid file type! ALF only supports .wav and .mp3 files');
}
trace('loaded in the audio file....');
}
// These functions notify the user of an error in loading the audio file
private function mp3LoadError(error:IOErrorEvent):void{
trace('Error loading mp3: '+error);
dispatchEvent(new Event(URL_ERROR));
}
private function waveLoadError(error:IOErrorEvent):void{
trace('Error loading wav file: '+error);
dispatchEvent(new Event(URL_ERROR));
}
/******************************************************************************
*
* AUDIO PLAYBACK FUNCTIONS
*
******************************************************************************/
// This is an internal function to play the current file again automatically when the end of the file is reached.
// If the boolean CONTINUE is true, then the file will loop, if it is false, the file will only be played once.
private function continueAudio():void{
switch(fileExt){
case "wav": loadedData.data.position = 44; // Reset to beginning of file
audioCh = audio.play(); // Start playback
audioCh.addEventListener(Event.SOUND_COMPLETE, audioComplete);
break;
case "mp3": mp3Position = 0; // Reset to beginning of file
mp3Bytes.length = 0; // Reset byte array
mp3Position += mp3Audio.extract(mp3Bytes, hopSize, mp3Position); // Extract audio
audioCh = audio.play(); // Start playback
audioCh.addEventListener(Event.SOUND_COMPLETE, audioComplete);
break;
}
}
/*
Group: Audio Playback
Function: loadNewSong
Use this function to load a new file into ALF for processing and playback.
Parameters:
filename - The filename (.wav or .mp3) of the audio file to be played. A new FILE_LOADED event will be dispatched
when the file has finished loading.
_startTime - specifies the offset (in msec) where playback should start in the track
*/
public function loadNewSong(filename:String, _startTime:uint):void{
startTime = _startTime;
// Sets the flag that this is a new file being loaded
DSP.endOfFile();
// Re-initialize the sound objects
audio = null;
audioCh = null;
audio = new Sound();
audioCh = new SoundChannel();
// Find file extension
fileExt = filename.substr(filename.length - 3, 4);
fileExt = fileExt.toLowerCase();
switch(fileExt){
case "wav": // Initialize wav objects
waveLoader = null;
waveLoader = new URLLoader(); // Initialize URL Looader
waveLoader.dataFormat = URLLoaderDataFormat.BINARY; // Set to binary format
waveLoader.addEventListener(Event.COMPLETE, waveLoaded); // Event for when file is loaded
waveLoader.addEventListener(ProgressEvent.PROGRESS, waveProgress); // Event for getting file loading data
waveLoader.addEventListener(IOErrorEvent.IO_ERROR, waveLoadError); // Event for file loading erros
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, wavAudioCallback); // Add event for each audio frame
var waveRequest:URLRequest = new URLRequest(filename); // Set filename to load
// Attempting to read in the wave file
waveLoader.load(waveRequest);
break;
case "mp3": // Initialize mp3 objects
var mp3Request:URLRequest = new URLRequest(filename); // Load filename
mp3Bytes = new ByteArray(); // For raw samples from file
mp3Bytes.endian = Endian.LITTLE_ENDIAN; // Set endianess for data processed in CPP
playBytes = new ByteArray(); // For playback of endian converted samples
playBytes.endian = Endian.BIG_ENDIAN; // Set endianess for playback in Flash
mp3Audio = new Sound(); // Sound object for audio file
STEREO = true;
fs = 44100;
// Attempting to read in the MP3 file
mp3Audio.addEventListener(IOErrorEvent.IO_ERROR, mp3LoadError); // Handle failed load
mp3Audio.addEventListener(Event.COMPLETE, mp3Loaded); // Dispatched when file is loaded
mp3Audio.addEventListener(ProgressEvent.PROGRESS, mp3Progress);
mp3Audio.load(mp3Request);
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, mp3AudioCallback); // Dispatched on each audio frame
break;
default: trace('Invalid file type! ALF only supports .wav and .mp3 files');
}
}
/*
Function: startAudio
A function to begin playback of an audio file. The FILE_LOADED event (<ALF Events>) must have been dispatched
and received by the class instantiating ALF prior to calling startAudio. Use startAudio to resume playback after
calling pauseAudio.
See Also:
<stopAudio()>,
<pauseAudio()>,
<Example>
*/
public function startAudio():void{
// When audio has already been played then stopped.
if(READY && STOP){
switch(fileExt){
case "wav": audioCh = audio.play();
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, wavAudioCallback);
audioCh.addEventListener(Event.SOUND_COMPLETE, audioComplete);
break;
case "mp3": audioCh = audio.play();
audio.addEventListener(SampleDataEvent.SAMPLE_DATA, mp3AudioCallback);
audioCh.addEventListener(Event.SOUND_COMPLETE, audioComplete);
break;
}
}
// First time being played or continuing after a pause
else if (READY){
audioCh = audio.play();
audioCh.addEventListener(Event.SOUND_COMPLETE, audioComplete);
}else if(!READY){
trace('ALF not initialized. Do not call startAudio() until file has loaded.');
}
STOP = false;
}
/*
Function: pauseAudio
A function to pause playback of an audio file. To resume playback, use startAudio.
See Also:
<startAudio()>,
<stopAudio()>
*/
public function pauseAudio():void{
audioCh.stop();
}
/*
Function: stopAudio
A function to stop playback of an audio file. This function removes the SampleDataEvent associated with the audio object.
The object will no longer call for more data to playback. Note that the SOUND_COMPLETE event will not be dispatched if
this function is called. When startAudio is called after stopAudio, the current file loaded will play from the beginning.
See Also:
<startAudio()>,
<pauseAudio()>,
<Example>
*/
public function stopAudio():void{
//DSP.clearAudioBuffers();
DSP.endOfFile();
switch(fileExt){
case "wav": audioCh.stop(); // Stopping playback
loadedData.data.position = 44; // Reset to beginning of file
break;
case "mp3": audioCh.stop(); // Stopping playback
mp3Bytes.length = 0; // Reset ByteArray
mp3Position = 0; // Reset to beginning of file
mp3Position += mp3Audio.extract(mp3Bytes, hopSize*2, mp3Position);
break;
}
STOP = true;
}
/******************************************************************************
*
* EVENTS
*
*******************************************************************************/
// These functions dispatch the PROG_EVENT to monitor the progress of a file
// being loaded. View the documentation for more information.
private function waveProgress(evt:ProgressEvent):void {
loadProgress = evt.bytesLoaded/evt.bytesTotal;
dispatchEvent(new Event(PROG_EVENT));
}
private function mp3Progress(evt:ProgressEvent):void {
loadProgress = evt.bytesLoaded/evt.bytesTotal;
dispatchEvent(new Event(PROG_EVENT));
}
// This function initializes sets all parameters in the C Library
private function waveLoaded(evt:Event):void {
loadedData = URLLoader(evt.target); // Establishing reference to object containing data read in from URLRequest
extractWaveHeader(loadedData); // Extract wave file header
// Need to set the frameSize based on desired userFrameRate and fs from the audio
if(userFrameRate > 40 || userFrameRate < 10){
trace("Invalid user-selected frame rate. Valid frame rates are between 10fps and 40fps.");
trace("Defaulting to 10fps");
hopSize = 1024;
}else {
hopSize = Math.round(fs/userFrameRate);
}
frameSize = 2*hopSize;
// If this is the first file loaded into the DATF, we use the constructor, if not we must call reInitializeChannel.
// The program will crash if you attempt to create a new DATF after already having created one.
if(!INITIALIZED){
// Initialize the DATF
DSP = new DATF(hopSize, STEREO, fs, frameLookAhead);
DSP.addEventListener(DSP.PROCESS_FRAME, processFrameHandler);
// Get the Reference to the cRAM data
cRAM = DSP.getCRAM();
audioPtrs = DSP.getChOutPtrs();
INITIALIZED = true;
}else{
// Re-initializing the channel changes the frame sizes based on the new sampling rate and reallocates
// C memory accordingly
if(DSP.getHopSize() != hopSize || numCh != DSP.getNumberOfChannels()){
DSP.reInitializeChannel(hopSize, fs, numCh, frameLookAhead); // New hopSize and fs are set in extractWaveHeader().
}
}
// Set ready for playback flag
READY = true;
dispatchEvent(new Event(FILE_LOADED));
// If the user wishes to begin playback from a different point other than the beginning of the track
// we need to adjust the starting position accordingly
if(startTime < 0 || (startTime/1000) > duration) {
trace('an invalid starting position was specified! playing from the beginning of the track ');
startTime = 0;
}
var startPosSamples:int = (startTime/1000)*fs;
var startPosBytes:int = startPosSamples*bytesPerSample;
//adjust the position to reflect the shift in start position
loadedData.data.position = loadedData.data.position + startPosBytes;
}
// This function initializes all parameters in the C Library
private function mp3Loaded(evt:Event):void{
// Stereo
numCh = 2;
STEREO = true;
// Need to set the hopSize based on desired userFrameRate and fs from the audio
if(userFrameRate > 40 || userFrameRate < 10){
trace("Invalid user-selected frame rate. Valid frame rates are between 10fps and 40fps.");
trace("Defaulting to 10fps");
hopSize = 1024;
}else {
hopSize = Math.round(fs/userFrameRate);
}
frameSize = 2*hopSize;
// If this is the first file loaded into the DATF, we use the constructor, if not we must call reInitializeChannel.
// The program will crash if you attempt to create a new DATF.
if(!INITIALIZED){
// Initialize the DATF
DSP = new DATF(hopSize, STEREO, fs, frameLookAhead);
DSP.addEventListener(DSP.PROCESS_FRAME, processFrameHandler);
// Get the Reference to the cRAM data
cRAM = DSP.getCRAM();
audioPtrs = DSP.getChOutPtrs();
INITIALIZED = true;
}else{
// Re-initializing the channel changes the frame sizes based on the new sampling rate and reallocates
// C memory accordingly
mp3Bytes.length = 0;
if(DSP.getHopSize() != hopSize || DSP.getNumberOfChannels() != numCh){
DSP.reInitializeChannel(hopSize, fs, numCh, frameLookAhead);
}
}
// determine what sample the user wants to start at.
if(startTime < 0 || (startTime/1000) > duration) {
trace('an invalid starting position was specified! ...playing from the beginning of the track ');
startTime = 0;
}
var startPosSamples:int = (startTime/1000)*fs;
// Extract samples of first frame and specify the offset
mp3Bytes.position = 0;
mp3Position = startPosSamples; // mp3's position works off of samples, not bytes
mp3Position += mp3Audio.extract(mp3Bytes, frameSize, mp3Position);
trace('ALF new song: fs = ' +fs, 'numCh = ' +numCh);
//Set ready for playback flag
READY = true;
dispatchEvent(new Event(FILE_LOADED));
}
// Dispatches the NEW_FRAME event
public function processFrameHandler(event:Event):void{
dispatchEvent(new Event(NEW_FRAME));
}
// Called when the file has completed
private function audioComplete(evt:Event):void{
// At end of file reset buffers/flags
DSP.endOfFile();
if(CONTINUE){
continueAudio();
}else{
switch(fileExt){
case "wav": loadedData.data.position = 44; // Reset to beginning of file
break;
case "mp3": mp3Bytes.length = 0; // Reset ByteArray
mp3Position = 0; // Reset to beginning of file
mp3Position += mp3Audio.extract(mp3Bytes, hopSize*2, mp3Position); // Extract samples
break;
}
}
STOP = true;
dispatchEvent(new Event(FILE_COMPLETE)); // Event to tell user file has finished
}
// Plays wav audio samples
private function wavAudioCallback(evt:SampleDataEvent):void {
var bufferReady:Boolean = false;
// As long as there is data left to read into C...we read it in and process the data
// by dispatching a new event.
var channelReady = 0;
if(loadedData.data.bytesAvailable != 0){
channelReady = DSP.setFrame(loadedData.data, "short");
}else {}
// Check the status of the buffers to see if they're ready for playback....
leftBufferStatus = DSP.checkOutputBuffer("left");
numSamplesToPlay = leftBufferStatus[1];
bufferReady = leftBufferStatus[0];
if(STEREO) {
rightBufferStatus = DSP.checkOutputBuffer("right");
numSamplesToPlay = Math.min(leftBufferStatus[1], rightBufferStatus[1]);
if(rightBufferStatus[0] && leftBufferStatus[0]) {
bufferReady = true;
} else {
bufferReady = false;
}
}
// If not ready for playback, load another frame and check again
while(!bufferReady){
channelReady = 0;
if(loadedData.data.bytesAvailable != 0){
channelReady = DSP.setFrame(loadedData.data, "short");
} else {}
leftBufferStatus = DSP.checkOutputBuffer("left");
numSamplesToPlay = leftBufferStatus[1];
bufferReady = leftBufferStatus[0];
if(STEREO) {
rightBufferStatus = DSP.checkOutputBuffer("right");
numSamplesToPlay = Math.min(leftBufferStatus[1], rightBufferStatus[1]);
if(rightBufferStatus[0] && leftBufferStatus[0]) {
bufferReady = true;
} else {
bufferReady = false;
}
}
}
// Play the samples
if(STEREO){
switch(fs){
case 44100: for(i = 0; i < numSamplesToPlay; i++){
cRAM.position = audioPtrs[0] + i*sizeofFloat; //position for leftCh
leftSample = cRAM.readFloat();
cRAM.position = audioPtrs[1] + i*sizeofFloat; //position for rightCh
rightSample = cRAM.readFloat();
// Write to output stream
evt.data.writeFloat(leftSample);
evt.data.writeFloat(rightSample);
}
break;
case 22050: for(i = 0; i < numSamplesToPlay; i++){
cRAM.position = audioPtrs[0] + i*sizeofFloat; //position for leftCh
leftSample = cRAM.readFloat();
cRAM.position = audioPtrs[1] + i*sizeofFloat; //position for rightCh
rightSample = cRAM.readFloat();
// Write to output stream
evt.data.writeFloat(leftSample);
evt.data.writeFloat(rightSample);
evt.data.writeFloat(0);
evt.data.writeFloat(0);
}
}
}else if (!STEREO){
switch(fs){
case 44100: for(i = 0; i < numSamplesToPlay; i++){
cRAM.position = audioPtrs[0] + i*sizeofFloat; //position for leftCh
leftSample = cRAM.readFloat();
// Write to output stream
evt.data.writeFloat(leftSample);
evt.data.writeFloat(leftSample);
}
break;
case 22050: for(i = 0; i < numSamplesToPlay; i++){
cRAM.position = audioPtrs[0] + i*sizeofFloat; //position for leftCh
leftSample = cRAM.readFloat();
// Write to output stream
evt.data.writeFloat(leftSample);
evt.data.writeFloat(leftSample);
evt.data.writeFloat(0);
evt.data.writeFloat(0);
}
break;
}
}else{
trace('ERROR: ALF can only handle mono or stereo files.');
}
}
// Plays mp3 audio samples
private function mp3AudioCallback(evt:SampleDataEvent):void {
var bufferReady:Boolean = false;
// As long as there is data left to read into C...we do that and process the data
// by dispatching a new event (in DATF)
var channelReady = 0;
mp3Bytes.position = 0;
if(mp3Bytes.length > 0){
channelReady = DSP.setFrame(mp3Bytes, "float");
}
// Check the status of the buffers to see if they're ready for playback....
leftBufferStatus = DSP.checkOutputBuffer("left");
rightBufferStatus = DSP.checkOutputBuffer("right");
numSamplesToPlay = Math.min(leftBufferStatus[1], rightBufferStatus[1]);
if(rightBufferStatus[0] && leftBufferStatus[0]){
bufferReady = true;
}
// Extract audio data from sound object If the inBuffer was not ready, we have not written data to C/C++ and
// consequently do not want to extract new data.
if(channelReady != 0){
mp3Bytes.length = 0;
mp3Position += mp3Audio.extract(mp3Bytes, hopSize, mp3Position); // Extract samples
}
// If not ready for playback, load another frame and check again
while(!bufferReady){
channelReady = 0;
mp3Bytes.position = 0;
if(mp3Bytes.length > 0){
channelReady = DSP.setFrame(mp3Bytes, "float");
}
//trace('channelReady = ' +channelReady);
// Check the status of the buffers to see if they're ready for playback....
leftBufferStatus = DSP.checkOutputBuffer("left");
rightBufferStatus = DSP.checkOutputBuffer("right");
numSamplesToPlay = Math.min(leftBufferStatus[1], rightBufferStatus[1]);
if(rightBufferStatus[0] && leftBufferStatus[0]) {
bufferReady = true;
} else {
bufferReady = false;
}
// Extract audio data from sound object. If the inBuffer was not ready, we have not written data to C/C++ and
// consequently do not want to extract new data.
if(channelReady != 0){
mp3Bytes.length = 0;
mp3Position += mp3Audio.extract(mp3Bytes, hopSize, mp3Position);
}
}
for(i = 0; i < numSamplesToPlay; i++){
cRAM.position = audioPtrs[0] + i*sizeofFloat; //position for leftCh
leftSample = cRAM.readFloat();
cRAM.position = audioPtrs[1] + i*sizeofFloat; //position for rightCh
rightSample = cRAM.readFloat();
// Write samples
evt.data.writeFloat(leftSample);
evt.data.writeFloat(rightSample);
}
}
/******************************************************************************
*
* DSP FUNCTIONS
*
******************************************************************************/
/*
Group: Audio Features
Values returned from all features are dependent upon the input audio. The style, genre,
and instrumentation play a significant role in the numbers returned from each function
but the production value (i.e. compression/mastering) also weighs heavily into what range
of values is returned, especially for the intensity.
Function: getIntensity
This function calculates the intensity of the current audio frame loaded into ALF. The
intensity is a measure of how much energy is in the current frame. If there are many
instruments playing loudly, this value will be large, for an ambient section of a song,
this value will be smaller.
Returns:
An Number which is the intensity value for the current frame. The range of values
will be dependent mostly upon the production value of the audio file.
*/
public function getIntensity():Number{
inten = DSP.getIntensity();
return inten;
}
/*
Function: getBrightness
Brightness is an approximation of the timbre. If there is high frequency content, such as
a horn section, then the brightness is higher, for low frequency, such as drum and bass, the
brightness value will be lower.
Returns:
A Number which is the brightness (in Hz) value for the current frame. Typical values will
be around several thousand hertz.
*/
public function getBrightness():Number{
cent = DSP.getCentroid();
return cent;
}
/*
Function: getFlux
This function calculates the change in frequency content for each frame. Instantaneous changes in
the audio content (both new sounds and sudden quiet) will produce large flux values.
Returns:
A Number which is the flux value for the current frame.
*/
public function getFlux():Number{
flux = DSP.getFlux();
return flux;
}
/*
Function: getBandwidth
This function calculates the bandwidth of the current audio frame loaded into ALF. The
bandwidth represents the range of frequencies present in the audio at the current frame.
This value gives an estimate of the instrumentation. A full band with drums, vocals, keys,
bass, guitar, synth, etc. will have a large bandwidth. An a solo cello performance will have
a smaller bandwidth.
Returns:
An Number which is the bandwidth (Hz) value for the current frame. Typical values
will be around several thousand hertz.
*/
public function getBandwidth():Number{
band = DSP.getBandwidth();
return band;
}
/*
Function: getRolloff
This function calculates the frequency ceiling of the current frame. Rolloff is the frequency below which
most of the instruments lie.
Returns: