Search code examples
androidservicestreammp3switch-statement

Changing URL in Android MP3 service MediaPlayer


I have a Service which starts playing MP3 stream in background in Android. There is a menu activity with channels select, and player activity, which starts to play the MP3 selected by button click. It uses MediaPlayer class. Here is how URL starts.

mp3Service.playSong(getBaseContext(),url);

Now, when coming back to the menu with URLs, I want to change the URL playing. I'd prefer not to stop the service and only change it's URL. Is it possible? I've read documentation of MediaPlayer, but not sure what to do, tried some variants.

How to switch to another URL? mp3Service.pauseSong(getBaseContext());

Then STOP, and mp3Service.playSong(getBaseContext(),newurl)?

////////////////////////////// PART OF THE CLASS

 public String currenturl="";

public void playSong(Context c, String url) {
        if (currenturl.equals(""))
        {
        if(!created){
            this.mplayer = MediaPlayer.create(c, Uri.parse(url));
            created = true;
            currenturl=url;
        }
            this.mplayer.start();
        }
        else
            {
            if (!currenturl.equals(url))
            {

                if(!created){
                    this.mplayer.stop();
                    this.mplayer = MediaPlayer.create(c, Uri.parse(url));
                    created = true;
                    currenturl=url;
                }
                    this.mplayer.start();


            }

            };
    }

public void pauseSong(Context c) {
        this.mplayer.pause();
    }

    //
    public void stopSong(Context c) {
        this.mplayer.stop();
    } 

Not so easy...


Solution

  • Regarding your comment, it's because created is true after the first play so you never execute your else logic. Here's how I would do it, I don't think there's any need to store a seperate created value.

    public String currenturl = "";
    
    public void playSong(Context c, String url) {
        if (currenturl.equals(url)) {
            // it's the same
        }
        else {
            // it's not the same
            currenturl = url;
        }
    }