Well, I've had a slight dilemma that can cause a sound to be thrown at the press of a button, and to release that sound to INSTANTLY. However, I still do not get the sound to stop instantly, it just stops instantly the first time I press and release soon after, but after that I press, release and the sound continues.
I used the SoundPool class to perform the sounds, and the onTouch event for each of the buttons ...
Follow the code
public class MainActivity extends AppCompatActivity {
private SoundPool mSoundPool;
private int sounddo;
protected void playMusicOnTouch(int streamId,MotionEvent event){
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mSoundPool.play(streamId, 1, 1, 1, 0, 1);
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
mSoundPool.stop(streamId);
}
}
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSoundDo = findViewById(R.id.btn_sounddo);
mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 2);
sounddo = mSoundPool.load(getApplicationContext(),R.raw.sounddo, 1);
btnSoundDo.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
playMusicOnTouch(sounddo,event);
return false;
}
});
}