问题
I've recently trying to build a simple android project. It will play a sound when the user click a button. When it was successfully compiled, the sound won't come off. I think it is the source code, but I don't know where the mistakes are
Here is my source code :
package com.jason.shootemup;
import java.util.Random;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class game extends Activity implements OnClickListener {
View shoot, reload;
int bullet = 5;
public static final Random r = new Random();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gun);
shoot = findViewById (R.id.shoot);
reload = findViewById (R.id.reload);
reload.setVisibility(2);
shoot.setOnClickListener (this);
shoot.setOnClickListener (this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.shoot :
shoot_sequence ();
break;
case R.id.reload :
Toast.makeText(this, "Reload !!", 10);
reload_sequence();
break;
}
// TODO Auto-generated method stub
}
private void shoot_sequence() {
if (bullet > 0) {
play_shoot_sound ();
Toast.makeText(this, bullet+" left !!", 10);
bullet = bullet - 1;
}
else {
reload.setVisibility(0);
shoot.setVisibility(2);
}
// TODO Auto-generated method stub
}
private void play_shoot_sound() {
MediaPlayer mp = MediaPlayer.create(this, R.raw.shoot);
mp.start();
mp.stop();
mp.release();
// TODO Auto-generated method stub
}
private void reload_sequence() {
play_reload_sound();
bullet = r.nextInt(4) + 1;
reload.setVisibility(2);
shoot.setVisibility(0);
// TODO Auto-generated method stub
}
private void play_reload_sound() {
MediaPlayer mp = MediaPlayer.create(this, R.raw.reload);
mp.start();
mp.stop();
mp.release();
// TODO Auto-generated method stub
}
}
Let me know the mistakes... THX for the help
回答1:
hi jason you r stopping and releasing as soon as the player is started. So stop it once it is completed. hopefully this code will help you
final MediaPlayer mPlayer=MediaPlayer.create(getBaseContext(), R.raw.reload);
mPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
//new Toast(getBaseContext());
mPlayer.release();
mPlayer = null;
}
});
来源:https://stackoverflow.com/questions/5715554/need-help-in-mediaplayer-class