简体   繁体   中英

SoundPool sound stops only once?

I have a Sound class:

  package dubpad.brendan;

  import android.media.SoundPool;

    public class Sound {
   SoundPool soundPool;
    int soundID;

    public Sound(SoundPool soundPool, int soundID) {
        this.soundPool = soundPool;
        this.soundID = soundID;
    }

    public void play(float volume) {
        soundPool.play(soundID, volume, volume, 0, -1, 1);
    }

    public void stop(int soundID){
        soundPool.stop(soundID);
    }


    public void dispose() {
        soundPool.unload(soundID);
    }


    }

and I have an activity that extends a button :

package dubpad.brendan;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.AttributeSet;

import android.view.MotionEvent;
import android.widget.Button;

public class TestButton extends Button {
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
int soundID = soundPool.load(getContext(), R.raw.dub1, 0);
Sound sound = new Sound(soundPool, soundID);


public TestButton(final Context context, final AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}



@Override
public boolean onTouchEvent(final MotionEvent event) {
  if(event.getAction()==MotionEvent.ACTION_DOWN){
sound.play(1);


 } 




if(event.getAction()==MotionEvent.ACTION_UP){
sound.stop(soundID);
}


    return super.onTouchEvent(event);
}

 }

On the first action down the sound plays, and on first action up the sound pauses. But every single action up after the 1st one doesn't pause the sound. In simple words, the pause only works once.

===EDIT=== (I think my original answer was wrong, changing it)

You need to change Sound class to return the streamId from play:

public int play(float volume) {
  return soundPool.play(soundID, volume, volume, 0, -1, 1);
}

And then you can store this value inside of TestButton:

if(event.getAction()==MotionEvent.ACTION_DOWN){
  mStreamId = sound.play(1);
} 

Then use mStreamId to stop the sound:

if(event.getAction()==MotionEvent.ACTION_UP){
   sound.stop(mStreamId);
}

The key here is that you want to call stop on the streamId , not the soundId . A soundId refers to the particular sound resource, but the streamId refers to a single instance of the sound playing. So if you play the same sound 3 times you have one soundId and three streamIds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM