Android Studio - SoundPool - 从 ImageView 中取出手指后停止声音
Android Studio - SoundPool - stop the sound after taking off the finger from ImageView
我有一个 ImageView。当我触摸它时,颜色会发生变化并且审查器声音开始播放。当我从 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;
};
};
您不应该为 stop() 传递 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;
}
我有一个 ImageView。当我触摸它时,颜色会发生变化并且审查器声音开始播放。当我从 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;
};
};
您不应该为 stop() 传递 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;
}