我在活动中有一个按钮,当我按下它时会播放声音。声音本身长2秒。它只在我按下按钮时播放。我想让用户可以按住按钮并播放声音,直到他释放按钮。我怎样才能做到这一点?这是我目前的代码。
package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class activity2 extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
mp.start();
}
} );
}
}
感谢!!!
答案 0 :(得分:2)
您的问题的解决方案是
的组合Triggering event when Button is pressed down in Android
和
play sound while button is pressed -android
即,您使用onClickListener而不是onTouchListener。
请尝试使用此功能(注意:我还将媒体播放器移出,因此您只需创建一次并反复使用它。)
public class activity2 extends Activity{
MediaPlayer mp = null;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
//back button that takes u to main.xml
Button next = (Button) findViewById(R.id.Back);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
} );
mp = MediaPlayer.create(activity2.this, R.raw.whippingsound);
//Button that plays sound (whippingsound)
Button sound = (Button) findViewById(R.id.sound);
sound.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
break;
case MotionEvent.ACTION_UP:
mp.pause();
break;
}
return true;
}
});
}