I am trying to set a sound for a touch for my game but there's an error on the line final MediaPlayer mp = MediaPlayer.create(this, R.raw.move); any suggestions? Thx
@Override
public boolean onTouchEvent(MotionEvent event) {
int x_aux = (int) (event.getX() / (this.getWidth() / x));
int y_aux = (int) (event.getY() / (this.getHeight() / y));
drawimage(x_aux, y_aux);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.move);
setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
mp.start();
}
});
return super.onTouchEvent(event);
}
The create(...)
method of MediaPlayer
requires a Context
as the first parameter. The problem is likely to be your Game class is a View
(which doesn't extend Context
) so using this
for the first parameter won't work.
You could try holding a reference to the Context
which is passed into the constructor. Under the private field private Paint caneta;
add one for the Context
. Example...
public class Game extends View {
private Cell[][] singlesquare = null;
int x = 3;
int y = 3;
private int l;
private int a;
private boolean whatdrawn = false;
private int playerwin = 3;
private Paint caneta;
private Context context; // ADD THIS LINE
Then in the constructor save a reference to the Context
passed in. Example...
public Game(Context context) {
super(context);
this.context = context; // ADD THIS LINE
Then when you create the Mediaplayer
use...
final MediaPlayer mp = MediaPlayer.create(context, R.raw.move);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.