【问题标题】:How to use stop() method in the SoundPool class?如何在 SoundPool 类中使用 stop() 方法?
【发布时间】:2016-09-26 19:58:28
【问题描述】:

我想在按住按钮时播放声音,但是当我松开按钮时,我希望停止播放相同的声音。像这样:

        private final SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);          

        ...

        btn1_row1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

                sp.play(sndTest, 1, 1, 0, 0, 1);

            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {

                sp.stop(sndTest); // It requires a Stream ID, not a Sound ID
            }
            return false;
        }
    });

我已经尝试了以下

final int streamId = sp.play(sndTest, 1, 1, 0, 0, 1);

sp.stop(streamId);

但它似乎不起作用,如果有人可以帮助我,提前谢谢。

【问题讨论】:

    标签: java android soundpool


    【解决方案1】:

    我想通了,因为我将流 ID 声明为 final,我无法在 onTouchListener() 中初始化它的变量,所以我将其声明为静态 int,如下所示:

    static int streamID;
    
    ...
    
    btn1_row1.setOnTouchListener(new View.OnTouchListener() {
    
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
    
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
    
                sndTestID = sp.play(sndTest, 1, 1, 0, 0, 1);
    
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                sp.stop(sndTestID);
            }
            return false;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      相关资源
      最近更新 更多