android-连续播放声音onTouch()
作者:互联网
我想通过onTouch连续播放枪声.我这样做是为了自动发出枪声.所以我有声音循环延迟的问题.不会产生真正的自动枪声效果.我的主要观点是,声音一遍又一遍地播放应该没有延迟.
我的代码是.
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mediaPlayer = MediaPlayer.create(RipleFire.this,
sounds[position]);
// if (mediaPlayer != null && mediaPlayer.isPlaying()) {
// mediaPlayer.stop();
// }
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imgflag.setImageResource(pistols[position]);
imgflag.setImageResource(pistolsAnimations[position]);
mediaPlayer.start();
mediaPlayer.setLooping(true);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
imgflag.setImageResource(pistols[position]);
}
return true;
}
解决方法:
他们可以根据您的问题解决
方法1
只需通过启动声音即可覆盖触摸方式.
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPlayer.setLooping(true);
mPlayer.start();
break;
case MotionEvent.ACTION_UP:
mPlayer.pause();
break;
}
return true;
}
//or
public boolean onTouch(View v, MotionEvent me) {
switch(me.getAction()) {
case MotionEvent.ACTION_DOWN:
if(!mPlayer.isPlaying()) mPlayer.start();
break;
case MotionEvent.ACTION_UP:
if(mPlayer.isPlaying()) mPlayer.stop();
break;
}
}
方法2
您还可以使用可运行的踏步或运行方法
Boolean IsPressed = false;
Button mbtn = (Button) findViewById(R.id.mbtn);
然后添加一个线程,在方法运行中添加此代码
@Override
public void run(){
while(!btnIsPressed){
myfunction();
}
}
现在,在方法onCreate中,添加一个侦听器以将布尔值更改为true,例如这样
mbtn.addOnClickListener( new OnClickListener(){
@Overrride
public void onClick(View v){
btnIsPressed = true;
}
});
编辑:
我已经包含了另一个方法3,在这里,只要您触摸视图,我们就会运行一个线程,如果是否触摸了视图,它会检查isPress或不按下,然后重复声音,直到您从触摸中释放视图为止.
在这里,我为您发布了完整的代码
public class Soundstuff extends Activity implements OnTouchListener {
SoundPool sP;
boolean isPress = false;
int gunshot = 0;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new View(this);
setContentView(v);
v.setOnTouchListener(this);
sP = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
gunshot = sP.load(this, R.raw.gunshot, 1);
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
/* do what you need to do */
if (isPress) {
sP.play(gunshot, 1, 1, 0, 0, 1);
/* and here comes the "trick" */
handler.postDelayed(this, 300);
} else {
}
}
};
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isPress = true;
handler.postDelayed(runnable, 300);
break;
case MotionEvent.ACTION_UP:
isPress = false;
handler.postDelayed(runnable, 300);
break;
}
return true;
}
}
希望这能解决您的问题.
标签:avaudioplayer,android-mediaplayer,android 来源: https://codeday.me/bug/20191121/2048574.html