问题
I'm trying to have a SoundPool play while a view object is being clicked.
I have successfully implemented it but found out that the sound of the click will lag.
I've been researching on StackOverFlow and on the internet for solutions and the best solution seems to be to have the SoundPool on a separate Thread.
I'm very new to the whole Thread thing and so I don't really know what to do at the moment.
I have followed THIS guide on creating a SoundPool thread, however, I don't know how to access it, or even to assign the clips that I wished to play.
Can someone please give me an example of how I should call the SoundPool thread to play my clip while an object in the view is being clicked.
Please find my onClick code below:
@Override
public boolean onTouch(View v, MotionEvent event) {
int actionPerformed = event.getAction();
switch(actionPerformed) {
case MotionEvent.ACTION_DOWN: {
if (Math.pow((event.getX() - a_Ball.getX()),2)
+ Math.pow((event.getY() - a_Ball.getY()), 2)
<= Math.pow(a_Ball.getDiameter(),2)) {
//pCheck = !pCheck;
if (pauseBall == false) {
SoundPool soundPool = new SoundPool(1,AudioManager.STREAM_MUSIC,1);
clickSound = soundPool.load(MainActivity.this, R.raw.click, 1);
/*soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
soundPool.play(clickSound,1.0f, 1.0f, 0, 0, 1.0f);
}
});*/
//Increase Ball Speed
sIncrease = true;
}
} else {
if (pauseBall == false) {
//set minus health when not touch on ball
health--;
TextView txtHealth = (TextView)findViewById(R.id.health);
String tempHealth = txtHealth.getText().toString();
tempHealth = getResources().getString(R.string.health) + String.valueOf(health);
txtHealth.setText(tempHealth);
}
}
break;
}
default:
return false;
}
return true;
} //onTouch end
Thanks in advance.
回答1:
You don't need threads to make sounds without lag. The lag comes from the loading of the sound file, try create the SoundPool and load the sound (soundPool.load
) in advance (e.g. onCreate
), then just call soundPool.play
in your onTouch
method.
回答2:
Ok, so instead of doing it in another class, I decided to do it in one class and created a new thread by myself. Seems to be working well enough.
I'll mark this thread as answer.
来源:https://stackoverflow.com/questions/23385968/calling-a-soundpool-thead-onclickevent