2015-09-23 3 views
1

У меня есть ImageView. Когда я прикасаюсь к нему, цвет меняется, и звук цензора начинает воспроизводиться. Когда я снимаю палец с ImageView, цвет снова меняется, и звук должен прекращать воспроизведение.Android Studio - SoundPool - остановить звук после снятия пальца с ImageView

Все работает нормально, но звук не останавливается. Я попытался поместить метод stop() в OnClickListener, но это не сработало.

Как я могу остановить звук, когда снимаю палец с ImageView?

btn_censor.setOnTouchListener(new OnTouchListener { 
@override 
public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
     btn_censor.setImageResource(R.drawable.btn_censor_focus);//Change color of the ImageView 

     //Parameters for sound 
     float vol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     float maxVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
     float leftVolume = vol/maxVol; 
     float rightVolume = vol/maxVol; 
     int priority = 1; 
     int loop = -1; //infinite loop 
     float normal_plaback_rate = 1f; 

     soundPool.play(censor_ID, leftVolume, rightVolume, priority, loop, normal_playback_rate);//Play the sound 
    } else if (event.getAction() == MotionEvent.ACTION_UP) { 
     btn_censor.setImageResource(R.drawable.btn_censor);//Change colour of the ImageView 
     soundPool.stop(censor_ID);//This should stop the sound 
    } 
    return false; 
    }; 
}; 

ответ

1

Нельзя передавать censor_ID для остановки(). Следующий код работает для меня:

int streamID; 

    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
    if (event.getAction() == MotionEvent.ACTION_DOWN) { 
     streamID = soundPool.play(myLoadedSoundID, 1, 1, 0, 0, 1); 
    } else if (event.getAction() == MotionEvent.ACTION_UP) { 
     soundPool.stop(streamID); 
    } 
    return true; 
    } 
Смежные вопросы