在MediaPlayer类中需要帮助

时间:2011-04-19 11:21:57

标签: android coding-style media-player

我最近尝试构建一个简单的android项目。当用户单击按钮时,它将发出声音。成功编译后,声音不会消失。我认为这是源代码,但我不知道错误在哪里

这是我的源代码:

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
}
}

让我知道错误...... THX的帮助

1 个答案:

答案 0 :(得分:0)

你好jason你在玩家开始后立即停止并释放。所以一旦完成就停止它。希望这段代码可以帮到你

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;



        }
    });