我正在创建一个小程序,当有人跳跃时播放马里奥跳跃的声音。我可以使用 Z 加速度使程序在达到某个值(如 10 m/s^2)时显示一条消息。我希望它从媒体播放器对象播放声音,但是当我创建媒体播放器对象时,它会使代码崩溃。我将在pastebin上发布代码。
public class MainActivity extends Activity implements SensorEventListener {
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
MediaPlayer mp = MediaPlayer.create(getBaseContext(),R.raw.jump); //Line 17
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm= (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration = (TextView) findViewById(R.id.acceleration);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acceleration.setText("X: " + event.values[0] + "\nY: " + event.values[1] + "\nZ: " + event.values[2]);
if (event.values[2] > 10.8 ) {
acceleration.setText("Z IS REALLY BIG!!");
}
}
}
添加第 17 行是程序崩溃的原因......