Implement Audio Streaming in Android Applications

Streaming an audio media consists to receive constantly data from a remote source and to deliver the audio data received to the end-user. Nowadays, everyone uses streaming platforms daily. For example, YouTube is a streaming video platform.

In this tutorial, you are going to discover how to implement audio streaming in an Android Application. Note that you can also discover this tutorial in video on YouTube :

To implement audio streaming in our Android Application, we are going to use the MediaPlayer API of the Android SDK. Like said in the Android official documentation, the MediaPlayer class can be used to control playback of audio/video files and streams. So, it’s perfect for our usage.

Create the User Interface

Write the Java Code

We install an OnClickListener on the button of our application. When a user will click on this button, we will check the state of the audio stream. If we are in pause, we will need to start the audio streaming. In this case, there is also two possibilities. First, we have not initialized the connection between our application and the remote audio source to stream. In this case, we will need to initialize the connection in a separate Thread thanks to a Player AsyncTask.

In the case where the audio streaming has just been paused, we will just have to restart if by calling the start method of the MediaPlayer instance created previously. If we are in play mode, we have to pause the MediaPlayer by calling its pause method.

Player AsyncTask

Then, we set an OnCompletionListener on the MediaPlayer. When the MediaPlayer will have terminated the audio to stream, we should call the stop method of the MediaPlayer and its reset method to let a future stream on this object.

Finally, we call the prepare method of the MediaPlayer which it lets us to connect our MediaPlayer to the remote audio source to stream.

Note that in the onPreExecute method of the Player AsyncTask, we show the ProgressDialog to the end-user and in the onPostExecute method, we hide the ProgressDialog and we will start the audio streaming by calling the start method of the MediaPlayer.

That gives us the following code for the Main Activity and the Player AsyncTask :

Last step is to try our Android Application and to enjoy the final result with an Audio Music File streamed :

Image for post
Image for post

To discover more tutorials on Android development, don’t hesitate to visit the SSaurel’s Channel on YouTube :

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store