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


    }

我有一个扩展按钮的 Activity :

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

 }

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

最佳答案

===编辑===(我认为我原来的答案是错误的,更改它)

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

关于android - SoundPool 声音只停止一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12936294/

相关文章:

android - original-package AndroidManifest 属性是做什么用的?

android - 在滚动 recyclerview 项目时,当 recyclerview 滚动时背景颜色发生变化

android - 如何使用Soundpool一键播放和停止声音

android - 在Android中实时录制和混合音频

android - 打开我的 Activity 3秒后,SoundPool无法播放

android - 将音频文件流式传输到 soundpool load() Android

android - 如何根据Android中的声音播放禁用和启用布局

android - 使用消息或基于接口(interface)的方法从 AsyncTask 返回 List<T>?

android - 无法在 react-native run-android 上的设备上安装应用程序

安卓三星计算器