cutecutebj
cutecutebj

Reputation: 179

android play raw file

I have an app that basically looks like a bomb, when user click on the numbers, it will make sounds with the following code

        final MediaPlayer mp = MediaPlayer.create(this, R.raw.c4_click);
            mp.start();

which works fine, and then when the numbers has been fully entered, user will then click on a button which will create another sound with

    final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.c4_plant);
            mp.start();

so now, my problem is when this "c4" has been planted, and another user press on the numbers again, the sounds are gone. Am i suppose to somehow stop the mediaplayer first? or what am i supposed to do here?

EDIT: i have changed the numbers click sound to this

  Button btn = (Button) view;
    if(mp != null){
        if(mp.isPlaying()){
            mp.stop();
            mp.release();
        }
        mp = null;
    }
    mp = MediaPlayer.create(MainActivity.this, R.raw.c4_beep1);
    mp.start();

and the button click sound to this

            if(mp != null){
                if(mp.isPlaying()){
                    mp.stop();
                    mp.release();
                }
                mp = null;
            }
            mp = MediaPlayer.create(MainActivity.this, R.raw.c4_plant);
            mp.start();

but it crashes after

EDIT: full class full code here my first android app, please don't mind about the programming style and such

Upvotes: 0

Views: 121

Answers (1)

Chintan Bawa
Chintan Bawa

Reputation: 1386

On Number Click

MediaPlayer mp = MediaPlayer.create(this, R.raw.c4_click);
mp.start(); 

On Button click use this code.

if(mp != null){
   if(mp.isPlaying()){
      mp.stop();
      mp.release();
   }
   mp = null;
}
mp = MediaPlayer.create(MainActivity.this, R.raw.c4_plant);
mp.start();

Upvotes: 2

Related Questions