问题
In the documentation it says:
If you're using your expansion files to store media files, a ZIP file still allows you to use Android media playback calls that provide offset and length controls (such as MediaPlayer.setDataSource() and SoundPool.load()).
I have 10 small .ogg files and I want to use SoundPool.load (FileDescriptor fd, long offset, long length, int priority) to load these audio files. I've written some code, but when I run it I get error message:
"Unable to load sample: (null)"
, and obviously the audio isn't played. Here is what I attempted:
public class MainActivity extends Activity {
SoundPool sounds;
boolean loaded = false;
int streamID;
int theId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.activity_main);
sounds = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
sounds.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool sp, int sid, int status) {
loaded = true;
}});
loadSounds();
playSound(theID);
}
private void loadSounds() {
AssetFileDescriptor descriptor = null;
try {
descriptor = getFileDescriptor(this, "audio_files/end_credits.ogg");
} catch (Exception e) {
} finally {
if (descriptor != null)
try{descriptor.close();} catch (IOException e) {}
}
theId = sounds.load(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength(), 1);
}
public static AssetFileDescriptor getFileDescriptor(Context ctx, String path) {
AssetFileDescriptor descriptor = null;
try {
ZipResourceFile zip = APKExpansionSupport.getAPKExpansionZipFile(ctx, 4, -1);
descriptor = zip.getAssetFileDescriptor(path);
} catch (IOException e) {
e.printStackTrace();
}
return descriptor;
}
private void playSound(int soundID){
if(loaded){
streamID = sounds.play(soundID, 1, 1, 1, 0, 1);}
}
}
回答1:
Ok, seems like the reason is audio isn't loading fast enough. I put playSound(theID); right after loadSounds(); whereas it needs couple seconds to load before it can be played. But the code is working up to that point.
来源:https://stackoverflow.com/questions/21299892/loading-soundpool-with-audio-from-apk-expansion-file