调用SoundPool Thead onClickEvent [英] Calling a SoundPool Thead onClickEvent
问题描述
我正在尝试在单击视图对象时播放SoundPool.
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.
我一直在研究StackOverFlow和互联网上的解决方案,最好的解决方案似乎是将SoundPool放在单独的线程上.
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.
我对整个Thread知识还很陌生,所以我现在真的不知道该怎么办.
I'm very new to the whole Thread thing and so I don't really know what to do at the moment.
我已按照此指南创建了SoundPool线程,但是,我不知道如何访问它,甚至不知道如何分配要播放的剪辑.
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.
有人可以给我一个例子,说明在单击视图中的对象时如何调用SoundPool线程播放剪辑.
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.
请在下面找到我的onClick代码:
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
谢谢.
推荐答案
您不需要线程即可毫无延迟地发出声音.滞后来自声音文件的加载,请尝试创建SoundPool并提前加载声音(soundPool.load
)(例如onCreate
),然后只需在onTouch
方法中调用soundPool.play
.
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.
这篇关于调用SoundPool Thead onClickEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!