Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming Audio Using Service

Please take a look at my simple three-methods Service class that streams audio and play it directly.

public class StreamService extends Service {

    private static final String TAG = "MyService";
    String url;
    MediaPlayer mp;

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");

        mp.stop();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");

        url = intent.getExtras().getString("url");
        try {
            mp.setDataSource(url);
            mp.prepare();
            mp.start();
        } catch(Exception e){}          
        return START_STICKY;
    }
}

In my activity, I have two buttons to play/stop the media file:

  • The playButton execute this:

    Intent i = new Intent(this, StreamService.class);
    i.putExtra("my_mp3_url_string");
    startService(i);
    
  • The stopButton execute this:

    stopService(new Intent(this, StreamService.class));
    

Now, I have some questions:

  1. how I can implement the pauseButton? I want to pause the media running in the Service
  2. Does my way of playing/stopping the media/Service correct ? Is there any better way?
  3. How I can (periodically) update my Activity's UI from my Service? do I need to add something?
like image 745
iTurki Avatar asked Dec 30 '25 16:12

iTurki


1 Answers

I would recommend not using the lifetime of the Service as a way to start and stop playback. Using that approach will mean that every time you want to start a new stream, the code will be slowed down even more by having to bring up a new Service. You can save some time by just having the same Service play everything. Though that doesn't mean it should remain running all the time.

To accomplish that (and to be able to pause), you'll need to bind to the Service after it is started. With the bound Service, you'll be able to make calls to it - such as pause, play, stop, etc.

Here are some links that should help you with what you're looking for:

  • Using a Service with MediaPlayer
  • Binding to a Service
like image 106
Aldryd Avatar answered Jan 02 '26 08:01

Aldryd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!