Search code examples
actionscript-3loopsaudioembedding

Actionscript 3 - embed array of sound files using a loop


I am using Actionscript 3 to create a music playing game. For this I have recorded about 20 notes for each instrument (also using Starling Framework and FlashDevelop, though those seem likely irrelevant to this question). I am currently loading notes for the default instrument by specifying each file path and embedding each of the ~20 sounds like this:

    [Embed(source = "../assets/1.mp3")]
    public var SOUND_1:Class;
    var sound:Sound = new SOUND_1() as Sound;
    _sounds[1] = sound;

    [Embed(source = "../assets/2.mp3")]
    public var SOUND_2:Class;
    var sound:Sound = new SOUND_2() as Sound;
    _sounds[2] = sound;

    [Embed(source = "../assets/3.mp3")]
    public var SOUND_3:Class;
    var sound:Sound = new SOUND_3() as Sound;
    _sounds[3] = sound;

    //... etc...

However, in order to embed sounds for different instruments I will need something more modular. I've written the below loop that I expected would load the sounds and store them in an array of objects (I am already using such an array in the app). The problem I have encountered is that the Embed tag does not seem to recognize the filename's extension when I use a string like this. If I hard code a filename into the EMBED line, then it will compile fine (though obviously it will load ~20 or so copies of the same sound every time).

        for (var i:int = 1; i < totalSounds + 1; i++) {
            var filename:String = '../pathtosounds/' + String(i) + '.mp3';
            [Embed(source = filename)]
            var MY_SOUND:Class;
            var sound:Sound = new MY_SOUND() as Sound;
            _sounds[i] = sound;
        }

Is there any way around this without manually typing each filename/filepath for every possible note and instrument?


Solution

  • Replacing the EMBED tags with a loop that imported new sounds effects allowed me to iterate through the list of files as desired. Below is the relevant code which is part of a larger method that replaces the current instrument with the one named in instrumentName:

            for (var i:int = 1; i < totalSounds + 1; i++){
                var sound:Sound = new Sound;
                sound.addEventListener(IOErrorEvent.IO_ERROR, onSoundLoadError);
                var request:URLRequest = new URLRequest('audio/'+instrumentName+'/'+i+'.mp3');
                sound.load(request);
                _sounds[i] = sound;
            }
    

    For this, I also had to move my "audio" folder, which contains a sub folder for each instrument, into the bin directory where my main .SWF file is located.

    I also had to import some additional packages from Flash and Feathers (Starling's additional UI framework). I am allowing the user to select a new instrument by using the PickerList component in Feathers - hence the associated error event in the code above.