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.

Here i show you only Activity file (StreamingMp3Player.java). If you want to see some other file from this Android project, please download the SOURCE.
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.




#1 by ReinD on 17/03/2011 - 22:53
Quote
Awesome! Very useful indeed. Thanks!
#2 by Igor on 11/04/2011 - 13:37
Quote
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
#3 by igor on 12/04/2011 - 09:47
Quote
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!
#4 by Igor on 12/04/2011 - 11:48
Quote
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.
#5 by Igor on 12/04/2011 - 11:58
Quote
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;
}
}
#6 by Igor on 12/04/2011 - 12:16
Quote
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.
#7 by Igor on 11/05/2011 - 15:06
Quote
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
#8 by Igor on 13/05/2011 - 20:47
Quote
Hi Igor,
Please check the internet connection on your device. If you use WiFi connection check the MAC filters in your WiFi router.
#9 by Igor on 16/05/2011 - 13:57
Quote
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
#10 by Igor on 16/05/2011 - 14:39
Quote
Igor, have you able to go to internet from Android Device from your local network?
#11 by Igor on 16/05/2011 - 14:45
Quote
Yes, I can go to internet from my device. The local network is perfectly.
#12 by Igor on 16/05/2011 - 14:53
Quote
Sorry, i don’t know solution. Try to read about best practies in Android Development.
#13 by Igor on 16/05/2011 - 15:50
Quote
Thank you Igor
#14 by andi on 23/05/2011 - 04:55
Quote
how to stream .m3u?
#15 by Igor on 23/05/2011 - 08:07
Quote
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.
#16 by Salvatore on 17/07/2011 - 22:10
Quote
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
#17 by pratik on 23/07/2011 - 11:48
Quote
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
#18 by Igor on 02/08/2011 - 16:48
Quote
Hi, Salvatore
I don’t know. Try to replase mp3 stream URL with your aa+ stream URL.
#19 by Igor on 02/08/2011 - 16:58
Quote
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
#20 by pratik on 02/08/2011 - 19:08
Quote
hey igor……yeah its working…..thnx frnd thnx a lot…..be in touch for this kind of help..thank you
#21 by newbie on 11/08/2011 - 08:21
Quote
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 :),
#22 by Jibran on 25/08/2011 - 01:50
Quote
I need the reference for streaming the live radio in action script kindly please consider it
#23 by Teardrop on 25/08/2011 - 11:50
Quote
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.
#24 by Igor on 01/09/2011 - 08:29
Quote
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.
#25 by Andrea on 06/09/2011 - 19:38
Quote
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!
#26 by DARK GHOOOST on 01/11/2011 - 11:01
Quote
how can I stream pass RTSP? any body help me!
#27 by Alejandro on 02/11/2011 - 21:12
Quote
Awesome!!!! :D
#28 by Rich Morey on 18/11/2011 - 23:07
Quote
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?
#29 by ChantZ on 26/11/2011 - 15:09
Quote
thanks igor,but you can make it with playlist?
#30 by Mike on 11/12/2011 - 18:33
Quote
Hi, anyone know how to play .mp4 from URL?
Thanks
Mike
#31 by Anggriawan on 30/12/2011 - 18:24
Quote
Thanks its very useful for me
#32 by tom on 03/01/2012 - 05:15
Quote
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
#33 by Yaqub Ahmad on 06/01/2012 - 15:48
Quote
Can you please check this issue ?
http://stackoverflow.com/questions/8681550/android-2-2-mediaplayer-is-working-fine-with-one-shoutcast-url-but-not-with-the
#34 by Frane Poljak on 12/01/2012 - 21:55
Quote
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
#35 by Anggriawan on 29/01/2012 - 20:09
Quote
how to make notification for musicplayer ?
#36 by hemanth on 01/02/2012 - 19:15
Quote
please give reference code for streaming video of .m3u format in android
#37 by priya on 15/02/2012 - 10:14
Quote
Hi,
Any one pl help me. If i drag the seekbar in the middle, it is going back and starts to play from starting.
#38 by priya on 15/02/2012 - 10:16
Quote
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();
}
}
}
}
};
#39 by Thirumal on 08/03/2012 - 11:59
Quote
Very Nice…
#40 by muks on 13/03/2012 - 14:43
Quote
Thank you for this nice tutorial never thought it can be this clear. Really benefitail
#41 by muks on 13/03/2012 - 14:45
Quote
Thank you for this nice tutorial never thought it can be this clear.
#42 by Anggriawan on 13/03/2012 - 16:35
Quote
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)
#43 by Igor on 13/03/2012 - 16:50
Quote
@Anggriawan
Could you please give me all stacktrace of this error.
#44 by hemanth on 13/03/2012 - 18:52
Quote
how to play large video without any delay and using url like http://…../abc.mp4 format file in android.
#45 by Rick on 21/03/2012 - 21:14
Quote
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.
#46 by rnash2112 on 01/04/2012 - 21:37
Quote
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….
#47 by Mehran on 04/04/2012 - 20:40
Quote
Thank you so much,
Does it work with Android 2.1 ?
#48 by Igor on 07/04/2012 - 13:44
Quote
Hi, Mehran
I didn’t try out.
#49 by Seth on 19/04/2012 - 21:05
Quote
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?