user3517855
user3517855

Reputation: 211

How do I call mediaplayer once only?

In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feeddetail);

        tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
        tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
        TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);

        recPath = (String) intent.getSerializableExtra("INTENT_PATH");
        tc_recPath.setText(recPath);


        mediaPlayer = new MediaPlayer();

        try {
            mediaPlayer.setDataSource(recPath);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
        }

        ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
        mClickButton1.setOnClickListener( new OnClickListener() {
             @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                 if (mediaPlayer !=null){
                        try {
                            mediaPlayer
                            mediaPlayer.prepare();
                            seekBar.setMax(mediaPlayer.getDuration());
                            mediaPlayer.start();

                            seekUpdate();
                            isPlaying = true;
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                }
             }
       });

        ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
        mClickButton2.setOnClickListener( new OnClickListener() {
             @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                 mediaPlayer.stop();
                 isPlaying = false;
             }

       });

Upvotes: 0

Views: 60

Answers (1)

Sahaab Zahid
Sahaab Zahid

Reputation: 28

I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing In that case you can do the following

In the activity You can override the onPause method and put mediaPlayer.stop() inside it

@Override
public void onPause() {
    super.onPause();
    mediaPlayer.stop();
}

Upvotes: 1

Related Questions