0

I have an application that has single activity and I know How to play a background music using the Media player. As I have only one activity so I think I really do not need to play this music in the service. so I have little confusion so this is what I want.

What I want :

In my app I have a single activity and some buttons in it. I want to play sounds of different length on button click. But Mean while I really do not want to stop the back ground music it should play in background on the same time.

So my Question are (based on my upper given requirements)

  1. Is it possible to play two sounds in such a way that they really do not disturb the other sound ?

  2. What is a appropriate way to do it ?

  3. I do not want to play the background music in service as I would give the mute button to mute the background music. So it would be difficult to handle the service with UI button? So whats the either way

If you have any code and idea please share me. Any Link would be appreciated. Thanks in Advance.

1 Answer 1

2

You can use Service with MediaPlayer

Service class -

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MusicService extends Service  implements MediaPlayer.OnErrorListener{

    private final IBinder mBinder = new ServiceBinder();
    MediaPlayer mPlayer;
    private int length = 0;

    public MusicService() { }

    public class ServiceBinder extends Binder {
         MusicService getService()
         {
            return MusicService.this;
         }
    }

    @Override
    public IBinder onBind(Intent arg0){return mBinder;}

    @Override
    public void onCreate (){
      super.onCreate();

       Player = MediaPlayer.create(this, R.raw.jingle);
       mPlayer.setOnErrorListener(this);

       if(mPlayer!= null)
        {
            mPlayer.setLooping(true);
            mPlayer.setVolume(100,100);
        }


        mPlayer.setOnErrorListener(new OnErrorListener() {

      public boolean onError(MediaPlayer mp, int what, int
          extra){

            onError(mPlayer, what, extra);
            return true;
        }
          });
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId)
    {
         mPlayer.start();
         return START_STICKY;
    }

    public void pauseMusic()
    {
        if(mPlayer.isPlaying())
        {
            mPlayer.pause();
            length=mPlayer.getCurrentPosition();

        }
    }

    public void resumeMusic()
    {
        if(mPlayer.isPlaying()==false)
        {
            mPlayer.seekTo(length);
            mPlayer.start();
        }
    }

    public void stopMusic()
    {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    @Override
    public void onDestroy ()
    {
        super.onDestroy();
        if(mPlayer != null)
        {
        try{
         mPlayer.stop();
         mPlayer.release();
            }finally {
                mPlayer = null;
            }
        }
    }

    public boolean onError(MediaPlayer mp, int what, int extra) {

        Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
        if(mPlayer != null)
        {
            try{
                mPlayer.stop();
                mPlayer.release();
            }finally {
                mPlayer = null;
            }
        }
        return false;
    }
}

In your Activity class use ServiceConnection

private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon =new ServiceConnection(){

    public void onServiceConnected(ComponentName name, IBinder
     binder) {
    mServ = ((MusicService.ServiceBinderbinder).getService();
    }

    public void onServiceDisconnected(ComponentName name) {
        mServ = null;
    }
    };

    void doBindService(){
        bindService(new Intent(this,MusicService.class),
                Scon,Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService()
    {
        if(mIsBound)
        {
            unbindService(Scon);
            mIsBound = false;
        }
    }
}

Starting, Pausing, Resuming and Stopping the music

Follow the steps

  1. First bind the service to the activity by calling doBindService on your activity's onCreate as passing an intent to the service.
  2. Start the service by an explicit Intent: Intent music = new Intent(); music.setClass(this,MusicService.class); startService(music);
  3. From your activity, wherever you want to pause, resume or stop music, call the corresponding service functions as follows: mServ.pauseMusic(); mServ.resumeMusic(); mServ.stopMusic();
  4. Don't forget to call doUnbindService from places where you want to unbind the service from the activity. An ideal place is the call to activity's onDestroy()method.
  5. In your application's AndroidManifest file, paste the following XML code:

"service android:name="MusicService" android:enabled="true"

I hope this will help you out.

4
  • great so this would keep playing in service and then with button i can create a local media player and play a sound ? Is it so ? May 5, 2016 at 8:18
  • Hmm ya but you will need to make a widget if you want everything to be done from outside rather than from activity. OR you can also do it in notification bar. It's all about how you need to execute your code May 5, 2016 at 8:19
  • no you didnt get my second Idea. All I mean I want background music to keep playing , and on button click , let say on button click a new sound play i.e "You have Clicked Next Button" so I want to play this sound on button click while keeping the background music to keep playing May 5, 2016 at 8:23
  • @AllayKhalil check this out stackoverflow.com/a/15931595/842607. The work around in your case may be you can make multiple services with same code and play them simultaneously. May 5, 2016 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.