need help in MediaPlayer class

你离开我真会死。 提交于 2020-01-17 05:12:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!