mahdi azarm
mahdi azarm

Reputation: 349

How to stop background media player

Hi i'm creating an app like sound cloud.there is a list of songs in main activity and when user click on one of these songs a new activity gets open and in that activity if user click on the play button the song start playing also if user return to the main activity the songs continue playing but if the user chose another song and play it the previous song continue playing with the new song.

How can i stop the previous song from playing in the background when user click on the play button of new song?

Here is the code of my audio player activity

public class Songs_Single extends AppMenu {
ListView lv;
static final String[] numbers = new String[] { "one", "two", "three",
        "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
        "seventeen", "eighteen", "nineteen", "twenty", "twenty one",
        "twenty two" };
ImageView cover;
ImageView playBtn;
ImageView prevBtn;
ImageView nextBtn;
SeekBar songSeekBar;
SeekBar volumeSeekBar;
ImageView actionbar_Post_Cover;
TextView actionbar_Title;
TextView actionbar_Subtitle;
TextView SongCurrentTime;
TextView SongDuration;
protected MediaPlayer mediaPlayer;
AudioManager audioManager;
int currentSec;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View contentView = inflater.inflate(R.layout.songs_single, null, false);
    drawerLayout.addView(contentView, 0);
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.songs_single_header, lv,
            false);
    ArrayAdapter adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, numbers);
    lv = (ListView) findViewById(R.id.Songs_Single_mahdi);
    lv.addHeaderView(header);
    lv.setAdapter(adapter);
    final ImageView logo = (ImageView)findViewById(R.id.actionbar_logo);
    logo.setVisibility(View.GONE);
    cover = (ImageView)findViewById(R.id.Songs_Single_Cover);
    actionbar_Post_Cover = (ImageView)findViewById(R.id.actionbar_Post_Cover);
    actionbar_Post_Cover.setVisibility(View.VISIBLE);
    actionbar_Title = (TextView) findViewById(R.id.actionbar_Title);
    actionbar_Subtitle = (TextView) findViewById(R.id.actionbar_Subtitle);
    actionbar_Subtitle.setVisibility(View.VISIBLE);
    playBtn = (ImageView)findViewById(R.id.Songs_Single_Controls_Controls_PlayBtn);
    nextBtn = (ImageView)findViewById(R.id.Songs_Single_Controls_Controls_NextBtn);
    prevBtn = (ImageView)findViewById(R.id.Songs_Single_Controls_Controls_PrevBtn);
    songSeekBar = (SeekBar)findViewById(R.id.Songs_Single_Controls_SeekBar_SeekBar);
    volumeSeekBar = (SeekBar)findViewById(R.id.Songs_Single_Controls_VolumeBar_VolumeBar);
    SongCurrentTime = (TextView) findViewById(R.id.Songs_Single_Controls_SongCurrentTime);
    SongDuration = (TextView) findViewById(R.id.Songs_Single_Controls_SongDuration);
    if (Values.coverUrl != ""){
        Picasso.with(getApplicationContext()).load(Values.coverUrl).into(cover);
        Picasso.with(getApplicationContext()).load(Values.coverUrl).into(actionbar_Post_Cover);
    }
    if (Values.postLikes != "")
        actionbar_Subtitle.setText(Values.postLikes+" Likes | "+Values.postDislikes+" Dislikes | "+Values.postViews+" Plays" );
    if ((Values.postTitle != "") && (Values.songName != ""))
        actionbar_Title.setText(Values.postTitle+" - "+Values.songName);


    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    volumeSeekBar.setMax(maxVolume);
    volumeSeekBar.setProgress(currentVolume);
    volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,0);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
    playBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                mediaPlayer.setDataSource(Values.songPlayerUrl);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Error playing song.",Toast.LENGTH_LONG).show();
            }
            mediaPlayer.start();
            int durationMin = ((mediaPlayer.getDuration())/1000) / 60;
            int durationSec = ((mediaPlayer.getDuration())/1000) % 60;
            final int currentMin = ((mediaPlayer.getCurrentPosition())/1000) / 60;
            currentSec = ((mediaPlayer.getCurrentPosition())/1000) % 60;
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        while (!isInterrupted()) {
                            Thread.sleep(1000);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                        SongCurrentTime.setText(currentMin+ " : "+currentSec);
                                }
                            });
                        }
                    } catch (InterruptedException e) {
                        //
                    }
                }
            };
            t.start();
            SongDuration.setText(durationMin+ " : "+durationSec);
        }
    });


 }
}

Upvotes: 0

Views: 679

Answers (2)

diogojme
diogojme

Reputation: 2359

The problem probably is happening because you are not stoping the media player that you create in your Songs_Single activity, then when you go to main activity, you are creating another Media Player instance and playing another song, it will play both media player simultaneously.

To solve this problem you have to use the same MediaPlayer to manage your songs in background, you can use a Servive or Intent Service to do it.

For work with services please read this answer

Upvotes: 1

Zapdos
Zapdos

Reputation: 627

mp is your mediaplayer.

if (mp != null) {
    mp.stop();
    mp.release();
    mp = null;
}

Upvotes: 0

Related Questions