Reputation: 1205
I have a bunch of sounds, assigned to a group of buttons, which i need to play. All my sounds are in asset folder. However, it does not work. The purpose is: to load from assetFodler and play that sounds. I will come out with code examples from my project:
//set up audio player
mSoundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//getting files lists from asset folder
aMan = this.getAssets();
try {
filelist = aMan.list("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For the purpose of do not having a lot of code lines, I created a basic procedure for loading and playing sounds:
public void loadSound (String strSound, int stream) {
try {
stream= mSoundPool.load(aMan.openFd(strSound), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
}
As you can see I pass file(stringName) and streamID.
Finally, here is how i use it:
case R.id.button1:
//if button was clicked two or more times, when play is still on im doing stop
mSoundPool.stop(mStream1);
loadSound(filelist[0],mStream1);
break;
When I run project, nothing happens and logcat says:
12-09 10:38:34.851: W/SoundPool(17331): sample 2 not READY
Any help would be appreciated.
UPD1: When I do it this way, without having loadSound procedure it works fine the following code is onCreate:
//load fx
try {
mSoundPoolMap.put(RAW_1_1, mSoundPool.load(aMan.openFd(filelist[0]), 1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and Onclick button:
//resourcePlayer.stop();
mSoundPool.stop(mStream1);
mStream1= mSoundPool.play(mSoundPoolMap.get(RAW_1_1), streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
I just dont want to have so much code lines, i wanted to make it look nice
Upvotes: 5
Views: 6677
Reputation: 132982
You will need to check file is loaded successfully before playing it using SoundPool.setOnLoadCompleteListener
Change your loadSound
method code as:
public void loadSound (String strSound, int stream) {
boolean loaded = false;
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
try {
stream= mSoundPool.load(aMan.openFd(strSound), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Is the sound loaded already?
if (loaded) {
mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
}
}
Upvotes: 3