Search code examples
androidandroid-mediaplayerandroid-resourcesapk-expansion-files

Playing sound files from expansion file


I have an expansion file with a series of sound files. The longer ones are .mp3 files while the shorter sound effects are .wav files. I pack them in a .zip file with no compression. I use the Zip File reader and downloader library provided by Google.

I'm opening the sound files like so:

MediaPlayer mPlayer;

...
AssetFileDescript asd = expansionFile.getAssFileDescriptor(fileName);
FileDescriptor soundFile = asd.getFileDescriptor();
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(soundFile);
mPlayer.prepare();
mPlayer.start();

The odd thing is that it plays the same sound file every single time. It seems to be whatever it finds first. The byte size for asd.getDeclaredLength() and asd.getLength() is exactly what it should be. This means the file descriptor is at least finding the file, but for some reason the MediaPlayer plays whatever random file it decides.

What exactly am I missing here? Any help would be greatly appreciated.

Thanks.


Solution

  • The first approximation is correct, except for when the zip file contains more than one file, then you should use:

    mPlayer.setDataSource(asd.getFileDescriptor(), asd.getStartOffset(), asd.getLength());
    

    You can get more information from this other question: Play audio file from the assets directory

    Please, also remember to close the AssetFileDescriptor just after setDataSource to media player:

    asd.close();
    

    http://developer.android.com/reference/android/media/MediaPlayer.html#setDataSource%28java.io.FileDescriptor,%20long,%20long%29