Java 按下按钮时播放声音-android
我有这个密码Java 按下按钮时播放声音-android,java,android,ontouchlistener,Java,Android,Ontouchlistener,我有这个密码 package com.tct.soundTouch; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.Bu
package com.tct.soundTouch;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
public class main extends Activity implements OnTouchListener {
private MediaPlayer mp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button zero = (Button) this.findViewById(R.id.button);
zero.setOnTouchListener(this);
mp = MediaPlayer.create(this, R.raw.sound);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
case MotionEvent.ACTION_UP:
mp.pause();
}
return true;
}
}
它确实有效,但并不像我预期的那样。声音只在我每次按下按钮时播放。我的想法是。当我按下按钮时,声音播放,当我停止动作(手指伸出按钮)时,音乐暂停
有什么想法吗
谢谢这应该行得通(我认为您的开关箱有问题):
它只是将return true添加到每个case、worksnowyup或break语句中。这两种方法都可以。@Fel你可能应该把它作为一个答案发布,如果这解决了你的问题,你应该接受它。请不要只发布代码,试着解释它。你是如何以及为什么改变它的。
@Override
public boolean onTouch(View v, MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
break;
case MotionEvent.ACTION_UP:
{
mediaPlayer.pause();
}
break;
}
return true;
}
public class MainActivity extends AppCompatActivity {
Button button;
MediaPlayer player;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
button = findViewById( R.id.Click );
button.setOnTouchListener( new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()== MotionEvent.ACTION_DOWN) {
player= MediaPlayer.create( MainActivity.this,R.raw.horn );
player.start();
}
else if(event.getAction()==MotionEvent.ACTION_UP){
player.stop();
player.release();
}
return true;
}
} );
}
}