繁体   English   中英

SoundPool声音仅停止一次?

[英]SoundPool sound stops only once?

我有一个声音课:

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

 }

在第一个动作中,声音播放,在第一个动作中,声音暂停。 但是在第一个动作之后的每个动作都不会暂停声音。 用简单的话来说,暂停只起作用一次。

===编辑===(我认为我的原始答案有误,将其更改)

您需要更改Sound类以从播放中返回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而不是soundId上调用stop soundId指的是特定的声音资源,而streamId指的是声音播放的单个实例。 因此,如果您播放相同的声音3次,则您将拥有一个soundId和三个streamId。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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