0

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);
        }
    });


 }
}
mahdi azarm
  • 340
  • 2
  • 7
  • 18

2 Answers2

1

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

Community
  • 1
  • 1
diogojme
  • 2,309
  • 1
  • 19
  • 25
  • i want to song continue playing until i hit the play button for the second song – mahdi azarm Dec 10 '15 at 18:08
  • You just need to `stop()` and `release()` your `MediaPlayer` that was playing the song, then you start your media player with the new song, `mediaPlayer.setDataSource(newsong); ` `mediaPlayer.prepare();` – diogojme Dec 10 '15 at 18:16
  • Make sure you was stopped the MediaPlayer instance that you create to play the first song, also considers you have the access to that media player from the main activity. – diogojme Dec 10 '15 at 18:22
  • tnx but i'm pretty new in android and i don't know a lot about service in android. i have to create a new class called BackgroundSoundService or just change my Songs_Single class as it said in that answer? – mahdi azarm Dec 10 '15 at 18:27
  • Yes, you have to create a Service separate then inside of the service you put your Media Player and methods that manage your songs. Please read about services and check the link i put in the answer, there have a example to how do a media player using service, and you can take a look here http://stackoverflow.com/a/21223481/1879661 to how you connect your activity to your service. Also considers the best and the right way using service to manage songs in the background. – diogojme Dec 10 '15 at 18:36
  • tnx a lot for your help it's work perfect.but it show stop and wait window after first start what is the problem? – mahdi azarm Dec 10 '15 at 19:16
  • how can i make it cache songs and play it from memory at the second time instead of load it from url again? – mahdi azarm Dec 10 '15 at 19:35
  • 1
    Service run in the UI Thread , if you are doing a lot of work in the service probably your app will show this popup, create and add this hard work inside a Thread or AsyncTask in your service. Learn about the concepts of Background Services. http://developer.android.com/training/run-background-service/index.html – diogojme Dec 10 '15 at 19:43
  • tnx i added mediaPlayer.setDataSource() and player.prepare() to the service on create method is it the problem? and if it is how can i add it from outside? – mahdi azarm Dec 10 '15 at 19:50
  • 1
    Yes, thats the problem, both have to be in a method outside of the onCreate and you have to call this method using an instance of the service in your activity. When you press the button play you access this method by this service instance in the activity. – diogojme Dec 10 '15 at 19:55
  • 1
    Of course, this is a complete project of an player app in Android. https://github.com/haibocheng/Player/blob/master/src/com/zanehuy/player/NowPlayingActivity.javaI will consider this topic ended. – diogojme Dec 10 '15 at 20:06
  • tnx but github gimme 404 error an says "not found". maybe the url is invalid please check it. – mahdi azarm Dec 11 '15 at 04:00
  • 1
    Link for the activity that have the connection with the service. https://github.com/haibocheng/Player/blob/master/src/com/zanehuy/player/NowPlayingActivity.java – diogojme Dec 11 '15 at 10:17
0

mp is your mediaplayer.

if (mp != null) {
    mp.stop();
    mp.release();
    mp = null;
}
Zapdos
  • 617
  • 1
  • 6
  • 23