biggboss2019
biggboss2019

Reputation: 300

How to implement completion listener in media player android image view

I am working on project that plays background music when user slides through the images. And musci stops when users reaches the last image. It also starts playing when user backslides. However, my song is short and I want to implement completion listener so that when first music ends the second music starts from the raw folder. My main problem is that I don't know how to implement it in my mainactivity.java. I have also read android official guidelines but it didn't helped. Please provide some help along with explanation...

My codes are the following

Mainactivity.java

    import android.app.Activity;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.support.v4.view.ViewPager;
    import android.support.v4.view.ViewPager.OnPageChangeListener;
    import android.view.Menu;

    import android.view.MenuItem;
    import android.widget.ShareActionProvider;

    public class MainActivity extends Activity {

        MediaPlayer oursong;
        ViewPager viewPager;
        ImageAdapter adapter;

        @Override
        public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_main);

             oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
             oursong.seekTo(0);
             oursong.start();

             viewPager = (ViewPager) findViewById(R.id.view_pager);
             adapter = new ImageAdapter(this);
             viewPager.setAdapter(adapter);


             viewPager.setOnPageChangeListener(MyViewPagerListener);
        }

        private ShareActionProvider mShareActionProvider;

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate menu resource file.
                getMenuInflater().inflate(R.menu.activity_main, menu);

                // Locate MenuItem with ShareActionProvider
                MenuItem item = menu.findItem(R.id.menu_item_share);

                // Fetch and store ShareActionProvider
                mShareActionProvider = (ShareActionProvider) item.getActionProvider();
                // Return true to display menu
                return true;
        }

        // Call to update the share intent
        private void setShareIntent(Intent shareIntent) {
                if (mShareActionProvider != null) {
                        mShareActionProvider.setShareIntent(shareIntent);
                }
        }

        private int pos = 0;
        @Override
        protected void onPause() {
                super.onPause();

               if(oursong != null){
                   pos = oursong.getCurrentPosition();
                   oursong.release();
                   oursong = null;
                }
        }

        @Override
        protected void onResume(){
              super.onResume();
             oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
             oursong.seekTo(pos); // You will probably want to save an int to restore here
             oursong.start();
        }


       private final OnPageChangeListener MyViewPagerListener = new OnPageChangeListener() {

                @Override
                public void onPageSelected(int pos) {
                  if (pos == adapter.getCount() - 1){
                     // adding null checks for safety
                     if(oursong != null){
                        oursong.pause();
                     }

                   } else if (!oursong.isPlaying()){ 

                    // adding null check for safety
                    if(oursong != null){
                        oursong.start();
                    }
                  }         
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                 // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

                }
            };

     }

Upvotes: 4

Views: 13031

Answers (2)

Salman Aziz
Salman Aziz

Reputation: 201

You have to set on completion listener on mediaplayer instance to determine the song is played

 mP.setOnCompletionListener(new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        try {

            mp.start();
            mp.setLooping(true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

Upvotes: 6

hannunehg
hannunehg

Reputation: 327

  1. The basic idea is that you need to change the states of the player in the correct order. OnCompletion you need to reset, change music, prepare async. OnPrepared you need to start playing.

To do that change this code:

    oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
    oursong.seekTo(0);
    oursong.start();

into

    MyTracksCustomClass tracks = new MyTracksCustomClass();

    MediaPlayer oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
    oursong.setLooping(false);
    oursong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource(MainActivity.this, tracks.getNextTrack);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mediaPlayer.prepareAsync();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        mediaPlayer.start();
                    }
                });
            }
        }
    });
  1. You need another class to manage getting the next track "MyTracksCustomClass" in which you should implement sth like:

    class MyTracksCustomClass {
        int trackIndex;
        HashMap<String, Integer> trackResourceIds;
        MyTracksCustomClass()
        {
            trackIndex = 1;
            // in case you only have two tracks
            trackResourceIds = new HashMap<String, Integer>();
            trackResourceIds.put("1",R.raw.a);
            trackResourceIds.put("2",R.raw.b);
        }
        public int getNextTrack() {
            // in case you only have two tracks
            trackIndex = (trackIndex > 3 )? 1 : trackIndex;
            return trackResourceIds.get(trackIndex++ +"");
    
        }
    }
    

Upvotes: 2

Related Questions