Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SoundPool.stop does not seem to work

I have created a class MySoundPool (I am using this class as sigelton, but don't think this is relevant as everyting else works). I am initianalizing SoundPool, a HashMap, and get the context for AudioManager. Thereafter I am loading two sounds. MySoundpool is used by method MySoundPool.playSound(int index, float rate) playSound clips rate to 0.5 <= rate >= 2.0 an executes statements

float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, index, 0, rate);

So far so good. Everything works fine. No it happens that playSound is called while the previous sound still plays, and I want to stop that before playing the new sound. Prior to the above code snippet I tried

mSoundPool.stop(mSoundPoolMap.get(index));

and

mSoundPool.autoPause();

with no success. The sound just continues to play to its end. Any comments will be appreciated

like image 866
Addi Avatar asked Nov 29 '22 10:11

Addi


2 Answers

I assume that you create a new SoundPool object in the constructor of your MySoundPool class?

If so then the first argument that SoundPool's constructor takes is the number of streams to allow at the same time. for example...

mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

That will allow 10 sounds to play at once so just change the 10 to a 1 and that should do it.

Edit: The stop() method takes a stream id as an argument, which should be the number returned from the play() method. You could try setting a variable equal to what play() returns and then use that variable when stopping the sound.

like image 113
DRiFTy Avatar answered Dec 06 '22 11:12

DRiFTy


Use the soundId to play a sound but use the streamId to stop it. These are not always the same number!

When you start the sound, store the returned streamId:

int myStreamId = mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, index, 0, rate);

Then use that streamId (not the soundId) to stop the sound:

mSoundPool.stop(myStreamId);
like image 27
Adam Pierce Avatar answered Dec 06 '22 10:12

Adam Pierce