Android SoundPool声音只停止一次?

Android SoundPool声音只停止一次?,android,soundpool,Android,Soundpool,我有一门声音课: 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 =

我有一门声音课:

  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);
    }


    }
我有一个扩展按钮的活动:

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);
}

 }
第一个动作向下时声音播放,第一个动作向上时声音暂停。但在第一个动作之后的每一个动作都不会暂停声音。简单地说,停顿只起作用一次

===编辑===(我认为我原来的答案是错的,修改了)

您需要更改声音类以从播放中返回streamId:

public int play(float volume) {
  return soundPool.play(soundID, volume, volume, 0, -1, 1);
}
然后您可以将此值存储在TestButton中:

if(event.getAction()==MotionEvent.ACTION_DOWN){
  mStreamId = sound.play(1);
} 
然后使用mStreamId停止声音:

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

这里的关键是要在
streamId
上调用
stop
,而不是
soundId
。soundId指的是特定的声音资源,而streamId指的是声音播放的单个实例。因此,如果将同一个声音播放三次,则会有一个soundId和三个StreamID。

那么,为什么要将
soundId
用作
stop()
方法的参数,而不将其用作
play()
方法的参数?对不起,stop()方法中不应该有这一点。这只是声音。停止();我还是有同样的问题。你看过你的日志了吗?每当出现问题时,SoundPool通常都会非常冗长。好的,
SoundPool.play()
方法会返回一些int,尝试使用stop和这个int。非常感谢Tim!但是我不知道如何记录streamID,也没有找到任何其他地方,请帮助我。我不明白这个问题,“记录streamID”是什么意思?您的代码看起来不错,但在调用soundPool.stop.Hey Tim之后需要再次调用soundPool.load!很抱歉,我的问题是如何获取play()函数返回的值?此外,加载函数在if(event.getAction()==MotionEvent.ACTION_DOWN)中不起作用{但是当我读到它时,显然我需要使用sound.stop(streamId);但每次我使用streamId时,它都会说它没有定义。所以我不知道该怎么做。streamId是由soundPool.play返回的,但您要在sound类中丢弃它。请参阅我编辑的答案。@ChrisBrendan