Reputation: 61
Recently I've been working on an android game, but have hit a problem when adding music and other sounds. I read that Mediaplayers are optimal for background music, which works well, and I read that Soundpool is optimal for short music clips like sound effects. However, I can't get the Soundpool to work, it appears that the Soundpool isn't even loading.
I did more research and found a lot of nightmare stories about Soundpool's lack of support, so should I just use a mediaplayer for all audio? Is this efficient?
//My Code
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int mySoundId, int status) {
loaded = true;
}
});
if(loaded==true){
soundId = soundPool.load(this, R.raw.sound1, 1);
soundPool.play(soundId, 1, 1, 1, 0, 1f);}
else{
System.exit(0);
}
//Forces the program to exit everytime
Upvotes: 2
Views: 485
Reputation: 1219
SoundPool#load
method is asynchronous, you should play sound after onLoadComplete
had been invoked
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int mySoundId, int status) {
soundPool.play(mySoundId, 1, 1, 1, 0, 1f);
}
});
soundPool.load(this, R.raw.sound1, 1);
Upvotes: 1
Reputation: 175
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int mySoundId, int status) {
loaded = true;
soundId = soundPool.load(this, R.raw.sound1, 1);
soundPool.play(soundId, 1, 1, 1, 0, 1f);
}
});
because your loaded variable will be always false, you should do the things within the onLoadComplete.
Upvotes: 0