Search code examples
actionscript-3flashmp3

How to join multiple mp3s into one downloadable mp3 file in Flash AS3?


I have a couple of short mp3 files that the user can reorganize on a timeline. After that, I want to save the result as one mp3 file, combining six short ones. In other projects I have done microphone recording, compressing to mp3 using the alchemy ShineMP3Encoder, and saving that as a file.

I see at least two approaches:

  1. Extracting all ByteArray data from the loaded Sound objects, concatenating that in a new ByteArray and compressing that with Shine. However the ByteArray from Sound.extract doesn't seem to be compatible with the encoder, telling me "Error : Input not a MS-RIFF file"
  2. Somehow combining the raw MP3 files without the need of decoding and encoding. But that would mean having to strip off file header info and such.

If impossible or very inefficient in Flash, I would consider a server side solution in PHP. So if that would be easy, please let me know.

Thanks!


Solution

  • It turns out it is in fact easy to combine multiple mp3 files. You can just concatenate their raw data and save it out as a new mp3 file. A few conditions apply:

    1. Make sure all compression settings are identical and non-dynamic. Bitrate, frequency, stereo/mono, etc.
    2. The end result's length indicated by your OS or an mp3 player might be wrong, and show the length of the first segment only. This is header-data. Most players, including Flash, will just play the whole file though, so in most situations this might not be a problem.

    In this example I'm using Greensock's LoaderMax library. DataLoader is the specific loader type you want to use (should be binary by default). *Note that I'm using the url as the name to identify the loader later, and some *_variables* need to be declared as class members* Of course you could use the native way or a different library to load your files too.

    for each ( var mp3FileURL : String in _mp3FileURLs )
    {
        var loader : DataLoader = new DataLoader( mp3FileURL, mp3FileURL ) );
        _preloadQueue.append( loader );
    }
    

    When loading the queue is complete, you can start processing the data from the loaders.

    _audioEditMP3 = new ByteArray();
    
    for each ( var mp3FileURL : String in _mp3FileURLs )
    {
        var content : * = _preloadQueue.getContent( mp3FileURL );
        _audioEditMP3.writeBytes( content );
    }
    

    You are now ready to save the file!

    var file : FileReference = new FileReference();
    file.save( _audioEditMP3, "myAudioCompilation.mp3" );