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

ReinD · 17 March, 2011 at 22:53

Awesome! Very useful indeed. Thanks!

Igor · 11 April, 2011 at 13:37

Thanks, very very useful. If I want to see the song´s name from a radio doing streaming…How I can do it? this radio uses Shoutcast. I am novice. Thank you

igor · 12 April, 2011 at 09:47

Hi, Igor.

Try this GET request:
http://yp.shoutcast.com/Metadata_Info1.php?surl=http://scfire-ntc-aa06.stream.aol.com:80/stream/1022

Where http://scfire-ntc-aa06.stream.aol.com:80/stream/1022 – streams URL

It can help you to get the current song title in Shoutcast stream.
Good luck!

Igor · 12 April, 2011 at 11:48

Thank you, thank you so much for your help. But how can I do this get request? I have no idea. Sorry but I am starting with Android. Sorry and thanks.

Igor · 12 April, 2011 at 11:58

You are welcome 🙂
There are many libraries which support HTTP requests. One of methods you can see below.
The HTTP GET request you can do with this class.

package com.hrupin;

import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;

class HttpGetDemo {
public static String getResp(String url) {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
String response = “Nothing”;
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return response;
}
}

Igor · 12 April, 2011 at 12:16

Thank you Igor. You have hight level of programatic knowledge. I envy you. I want that the song´s name will display in my layout but I am confused, I don´t know where I have to put the code that you have write to me and I don´t know how I can do this.
Sorry, I am disturbing you and sorry for my english too. Thank you, you are very helpful.

Igor · 11 May, 2011 at 15:06

Hello, if we use this example with Shoutcast url will work? If I use in the emulator yes but if I use in a device no. My device has 2.2 froyo. You know any solution?
Thank you

Igor · 13 May, 2011 at 20:47

Hi Igor,
Please check the internet connection on your device. If you use WiFi connection check the MAC filters in your WiFi router.

Igor · 16 May, 2011 at 13:57

Thank you Igor. But my computer goes with wifi too and works great on the emulator. My radio´s url is http://94.75.234.135:8052/ if you want to try! thank you again

Igor · 16 May, 2011 at 14:39

Igor, have you able to go to internet from Android Device from your local network?

Igor · 16 May, 2011 at 14:45

Yes, I can go to internet from my device. The local network is perfectly.

Igor · 16 May, 2011 at 14:53

Sorry, i don’t know solution. Try to read about best practies in Android Development.

Igor · 16 May, 2011 at 15:50

Thank you Igor

andi · 23 May, 2011 at 04:55

how to stream .m3u?

Igor · 23 May, 2011 at 08:07

m3u is the playlist file which contains list of media files/streams http://en.wikipedia.org/wiki/M3U .To stream this file, i think, you need to create some adapter for Android MediaPlayer class which parsed m3u and send streams to instance of MediaPlayer to play it.

Salvatore · 17 July, 2011 at 22:10

Hi, i’ve used your code for a project for my radio streaming online. That’s ok but, now, i would to change my stream type from mp3 64k to aac+ 64k because it’s better. My question is, do your code play aac+ ?

thank you very much

Salvatore

pratik · 23 July, 2011 at 11:48

Hi…its very useful and working fine..but I want to know how to stop that media player???.
I am using mediaPlayer.stop() it stops the media but buffering is still goin on…and after pressing stop if I press play then its not working…..Please tell me that issue. I am new in Android so dont know more about this…thnx in advance and waiting for your response

Igor · 2 August, 2011 at 16:48

Hi, Salvatore
I don’t know. Try to replase mp3 stream URL with your aa+ stream URL.

Igor · 2 August, 2011 at 16:58

Hi, practic
In your case try to use reset() method from MediaPlayer

public void reset ()

Since: API Level 1
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().

Hope, it’s helps

pratik · 2 August, 2011 at 19:08

hey igor……yeah its working…..thnx frnd thnx a lot…..be in touch for this kind of help..thank you

newbie · 11 August, 2011 at 08:21

Can this app work with OS prior to 2.2 ? and how can i implement a progress dialog popup to show that the media player need to buffer while playing ? is there any callback method from media player that can i use that inform me that the media player is in buffering state ?

thanks in advance :),

Jibran · 25 August, 2011 at 01:50

I need the reference for streaming the live radio in action script kindly please consider it

Teardrop · 25 August, 2011 at 11:50

How can i change the url to play another song…ive tried changing it in the string.xml file but i cant get it to run.

Igor · 1 September, 2011 at 08:29

Hi, Teardrop
Could you please give me url of your song. I want check it.
If it’s confidential you can send me an email.

Andrea · 6 September, 2011 at 19:38

Hi to all!

Thanks a lot for this useful tutorial.
I try to understand something about Android and streaming and with your knowledge’s sharing I begin to know something about it!!!

To stream radio url, change the data source (in onClick(View v) ).
Use:
mediaPlayer.setDataSource(“yourURL”);
Instead of:
mediaPlayer.setDataSource(editTextSongURL.getText().toString());

I see a little problem (but i don’t know how can i solve it, sorry).
When you change the orientation and you play the .mp3, the image button change (if it shows Pause image, return to Play image), then it is possible to start the file for second time.
Is it possible to fix it, please?

I try to add a volume bar. But… i don’t know how… eheh (I started studying Android by very little and.. i can learn from people who are prepared and available as Igor).
Any suggestions will be much appreciated.

Thanks again for your work!

DARK GHOOOST · 1 November, 2011 at 11:01

how can I stream pass RTSP? any body help me!

Alejandro · 2 November, 2011 at 21:12

Awesome!!!! 😀

Rich Morey · 18 November, 2011 at 23:07

I am trying to use this code to load a Shoutcast stream but it crashes saying that the server didn’t specify a duration which is correct because it is a live stream. Any help for that?

ChantZ · 26 November, 2011 at 15:09

thanks igor,but you can make it with playlist?

Mike · 11 December, 2011 at 18:33

Hi, anyone know how to play .mp4 from URL?
Thanks
Mike

Anggriawan · 30 December, 2011 at 18:24

Thanks its very useful for me

tom · 3 January, 2012 at 05:15

hi igor thanks lot it works very well ,really help me lot ,there is one question that when i press back key then the activity finish but the mediaplayer is still playing .i just wondering the activity life term does not affect the mediaplayer’s instance? does this relate to the JVM GC ? i am a green hand in android .thanks again

Frane Poljak · 12 January, 2012 at 21:55

Hi,

first, thank you for tjis example cause i lost 2 days trying to make this work before i found this. but also i have some issues.

i tried this on emulator and the song (i put another url) is actually playing but it’s slow and discontinuous. Also, I put it in another activity that is run from the main activity by startActivityForResult. I also added a button to exit (return to main activity) and in it’s onClick event i put:

exButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.reset();//tried with and without this
mediaPlayer.release();
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});

Music stops playing, but when returned in main activity it throws an exception and exits.
So, i have 2 questions:
1.) why is it slow and discontinuous and does it have anything to do with the fact it’s run on emulator?
2.) what else do I have to do to completely free the MediaPlayer and any other objects so i can return to main activity, and later run this activity again without errors?

Thank you

Anggriawan · 29 January, 2012 at 20:09

how to make notification for musicplayer ?

hemanth · 1 February, 2012 at 19:15

please give reference code for streaming video of .m3u format in android

priya · 15 February, 2012 at 10:14

Hi,

Any one pl help me. If i drag the seekbar in the middle, it is going back and starts to play from starting.

priya · 15 February, 2012 at 10:16

pl refer this seekbar listener,

private SeekBar.OnSeekBarChangeListener mBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
if (getMusicService().isPlaying()) {
getMusicService().seekTo(progress);
} else {
try {
start();
getMusicService().seekTo(progress);
} catch (Exception e) {
e.printStackTrace();
}
}
}

}
};

Thirumal · 8 March, 2012 at 11:59

Very Nice…

muks · 13 March, 2012 at 14:43

Thank you for this nice tutorial never thought it can be this clear. Really benefitail

muks · 13 March, 2012 at 14:45

Thank you for this nice tutorial never thought it can be this clear.

Anggriawan · 13 March, 2012 at 16:35

how to fix this error ??

03-13 22:18:00.993: E/MediaPlayer(405): start called in state 0
03-13 22:18:00.993: E/MediaPlayer(405): error (-38, 0)
03-13 22:18:01.023: E/MediaPlayer(405): Error (-38,0)

Igor · 13 March, 2012 at 16:50

@Anggriawan

Could you please give me all stacktrace of this error.

hemanth · 13 March, 2012 at 18:52

how to play large video without any delay and using url like http://…../abc.mp4 format file in android.

Rick · 21 March, 2012 at 21:14

Great Tut. If you can indulge me. Say I have several .mp3s (5 or 6) how do I get them to all play in order and/or use a “next” or “previous” button? If they are all in the same directory on my server.

rnash2112 · 1 April, 2012 at 21:37

First off let me just say AWESOME TUTORIAL! Very informative and useful. If you are still following these Igor thank you very much!

I am using your code as a basis for streaming secure audio from a URL and attempting to record that audio to the device as it is streaming. How would your code be modified to allow this to happen?

Thanks so much….

Mehran · 4 April, 2012 at 20:40

Thank you so much,
Does it work with Android 2.1 ?

Igor · 7 April, 2012 at 13:44

Hi, Mehran
I didn’t try out.

Seth · 19 April, 2012 at 21:05

How can I get multiple players on one screen. Right now this code only displays one player but I want to have 8 is this possible?

saleeh · 17 June, 2012 at 14:17

thank you very much

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.