Example of streaming mp3 mediafile from URL with Android MediaPlayer class

Published by Igor Khrupin on

Few days ago i tried to make my Android app can play music from URL.

The Android API give to us a very useful class. Here i want show you how to make  the streaming m3 mediaplayer using MediaPlayer class from Android API. This app use Android 2.2.

Below you can see the UI of this app. It’s very simple. Also below you can get the link for downloading source code

Here i show you only Activity file (StreamingMp3Player.java).

package com.hrupin.streamingmedia;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;

import com.hrupin.media.R;

public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
	
	private ImageButton buttonPlayPause;
	private SeekBar seekBarProgress;
	public EditText editTextSongURL;
	
	private MediaPlayer mediaPlayer;
	private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
	
	private final Handler handler = new Handler();
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }
    
    /** This method initialise all the views in project*/
    private void initView() {
		buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
		buttonPlayPause.setOnClickListener(this);
		
		seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);	
		seekBarProgress.setMax(99); // It means 100% .0-99
		seekBarProgress.setOnTouchListener(this);
		editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
		editTextSongURL.setText(R.string.testsong_20_sec);
		
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnBufferingUpdateListener(this);
		mediaPlayer.setOnCompletionListener(this);
	}

	/** Method which updates the SeekBar primary progress by current song playing position*/
    private void primarySeekBarProgressUpdater() {
    	seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
		if (mediaPlayer.isPlaying()) {
			Runnable notification = new Runnable() {
		        public void run() {
		        	primarySeekBarProgressUpdater();
				}
		    };
		    handler.postDelayed(notification,1000);
    	}
    }

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.ButtonTestPlayPause){
			 /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
			try {
				mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
				mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer. 
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
			
			if(!mediaPlayer.isPlaying()){
				mediaPlayer.start();
				buttonPlayPause.setImageResource(R.drawable.button_pause);
			}else {
				mediaPlayer.pause();
				buttonPlayPause.setImageResource(R.drawable.button_play);
			}
			
			primarySeekBarProgressUpdater();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v.getId() == R.id.SeekBarTestPlay){
			/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
			if(mediaPlayer.isPlaying()){
		    	SeekBar sb = (SeekBar)v;
				int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
				mediaPlayer.seekTo(playPositionInMillisecconds);
			}
		}
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		 /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
		buttonPlayPause.setImageResource(R.drawable.button_play);
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
		seekBarProgress.setSecondaryProgress(percent);
	}
}


I hope it will be useful for you.

Please download if you want to see some other file from this Android project.

Download it from github

75 Comments

mian · 25 June, 2012 at 10:37

Hi, Igor.

Thanks a lot, nice and useful tutorial. Good job.

May i ask you how can we set the autoplay please? I’m trying to figure out how to start streaming automatically when you open the program but… I have not yet understood how to do … hehe
Thanks again.

Mountanous Maverick · 3 August, 2012 at 14:27

nice site the text becomes a bit hard to read on your background after a while tho. jus a friendly suggestion =)

fahmi · 4 August, 2012 at 12:03

Thanks, brother

Igor · 4 August, 2012 at 12:43

Hello Mountanous Maverick,
Thanks!

Linus · 29 August, 2012 at 23:18

Hi,

Very new to Android development. Cannot figure out problem in downloaded sample code. Eclipse says the import com.hrupin.media.R cannot be resolved. Also many mentions of R cannot be resolved to a variable. Sounds like basic problem but I don’t know what I’m missing.

Cheers

Igor · 30 August, 2012 at 16:16

Hi Linus,

1. Check your Android SDK connection in Eclipse prefferences.
2. Clean your project
3. If it don’t help – delete bin dir manullay

Thirumal · 30 August, 2012 at 18:01

Thank You Very much

mario · 4 January, 2014 at 11:50

good job man

Lavanya · 6 February, 2014 at 12:39

Hi, I am getting a delay of some seconds before the audio is started. Can you please let me know the issue. I have tried the same code. After I call prepareAsync(), its calling start() after about 24seconds. Thank you.

rahulbawa · 10 February, 2014 at 16:13

Hi
I am just thinking that if the server will get the request and keep writing music bytes on the client’s output stream and may be the setDataSource method process what’s being written onto it and plays it.
Am I thinking in the right way?
So if above is correct then I’ll have to write some server code too?

Crashouille · 15 March, 2014 at 16:27

Hi !

First of all, thanks for this great article. This was exactly what I was looking for. However, it seems that the source code in your GIT repository has since changed to become a video player. Is there a way, by any chance, to get the original code fitting this article ?

Thanks ahead for your answer.

Tolbxela · 3 June, 2014 at 15:49

I have recreated the sample of Android Streaming Mp3 Player.
The code can be downloaded here: https://github.com/tolbxela/samples/tree/Android-Streaming-Mp3-Player/android/Streaming_Audio_Player

Christian · 24 August, 2014 at 03:29

Hi,

Thanks for the this. I still got an issue with a device running on 2.3.6. It gives me error (1, -4) while another device with 4.2 works fine.

    Igor Khrupin · 26 August, 2014 at 18:48

    Hi Christian,

    Could you please send logcat from your device? When I get it then I can look what is happened.

    Thanks,
    Igor

Kirti Avaiya · 2 September, 2014 at 11:04

Its very good example, saves my days to search and research , very great tutorial
Thanks,
🙂

abdul · 18 September, 2014 at 12:29

how to download this project?

Srikanth · 5 December, 2014 at 13:29

Hi

Thanks for very good tutorial. Plz Can u tell me ” How to show progress dialog ” before first download.

Thanks.

Bhavin Soni · 11 June, 2017 at 20:12

Awesome Example Of MediaPlayer
Thanks

Darshan · 16 June, 2017 at 12:58

Hey Thanks for this tutorial it was easy to understand
Its totally Working Fine but when i click play it will buffer first i have to click second time for play the song how to buffer and playing together ..??

Aakash · 17 December, 2017 at 11:32

Nice Sir
Its really nice but i have 3 to 4 songs and when i play song it will work fine but when i am going back and come again the it is does not shows the current length of song it is restart but song is played continue

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.