Home Android Media Player playing multiple songs together
Reply: 0

Android Media Player playing multiple songs together

user7446
1#
user7446 Published in May 22, 2018, 12:11 am

I am writing a Church Application, in which i am providing Music Player functionality, and almost done with my requirement, but facing small issue.

How i have implemented my Music Player:

  1. Listing Audio songs available in SD Card (path like: Environment.getExternalStorageDirectory() + "/Church Application/Prayers")
  2. Once user do tap on any of the Audio then launching Media Player
  3. In Media Player screen i am providing navigation to user to go back to Audio List
  4. User came back and now selected some other song to listen (here i am facing problem, user will be able to play new selected song, but old song also playing, whereas only last selected song would be play at a time, but in my case both the songs are playing)

PlayListActivity.java:-

    // selecting single ListView item
    ListView lv = getListView();
    // listening to single listitem click
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting listitem index
            int songIndex = position;

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    MediaPlayerActivity.class);
            // Sending songIndex to PlayerActivity
            in.putExtra("songIndex", songIndex);
            setResult(100, in);
            startActivity(in);
            // Closing PlayListView
            finish();
        }
    });

MediaPlayerActivity.java:-

    int value ;

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


                mp = new MediaPlayer();
            songManager = new SongsManager();
            utils = new Utilities();

            songProgressBar.setOnSeekBarChangeListener(this); // Important
            mp.setOnCompletionListener(this); // Important

            songsList = songManager.getPlayList();

            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                value = extras.getInt("songIndex");
            }

            playSong(value);


            btnPlay.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // check for already playing
                    if (mp.isPlaying()) {
                        if (mp != null) {
                            mp.pause();
                            // Changing button image to play button
                            btnPlay.setImageResource(R.drawable.btn_play);
                        }
                    } else {
                        // Resume song
                        if (mp != null) {
                            mp.start();
                            // Changing button image to pause button
                            btnPlay.setImageResource(R.drawable.btn_pause);
                        }
                    }

                }
            });

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            currentSongIndex = data.getExtras().getInt("songIndex");
            // play selected song
            playSong(currentSongIndex);
        }

    }

    public void playSong(int songIndex) {
        // Play song
        try {

            mp.reset();
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            mp.prepare();
            mp.start();
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);

            // Changing Button Image to pause image
            btnPlay.setImageResource(R.drawable.btn_pause);

            // set Progress bar values
            songProgressBar.setProgress(0);
            songProgressBar.setMax(100);

            // Updating progress bar
            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mp.getDuration();
            long currentDuration = mp.getCurrentPosition();

            // Displaying time completed playing
            songCurrentDurationLabel.setText(""
                    + utils.milliSecondsToTimer(currentDuration));

            // Updating progress bar
            int progress = (int) (utils.getProgressPercentage(currentDuration,
                    totalDuration));
            // Log.d("Progress", ""+progress);
            songProgressBar.setProgress(progress);

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);
        }
    };

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromTouch) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // remove message Handler from updating progress bar
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(),
                totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);

        // update timer progress again
        updateProgressBar();
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {

        // check for repeat is ON or OFF
        if (isRepeat) {
            // repeat is on play same song again
            playSong(currentSongIndex);
        } else if (isShuffle) {
            // shuffle is on - play a random song
            Random rand = new Random();
            currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
            playSong(currentSongIndex);
        } else {
            // no repeat or shuffle ON - play next song
            if (currentSongIndex < (songsList.size() - 1)) {
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            } else {
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // if one of the volume keys were pressed
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
                || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        }
        // propagate the key event
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mp.release();
    }

}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306868 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO