Introduction

NOTE #1: This tutorial was written for Android v1.0.  I have just updated the Android streaming media player tutorial/code to v1.5 (Cupcake) with some additional information on the updated code.  You should read that post as well as this one.

NOTE #2: This tutorial is about progressive audio.  If you want to stream live media, then please read my post on live and progressive streaming with Android.

This is a long tutorial, but for those of you that have been struggling with streaming of .mp3 audio to Google’s Android’s MediaPlayer, then I hope this tutorial proves useful as you finalize your entries into Google’s Android Challenge

This tutorial will show how to roll your own streaming audio utility for Android’s MediaPlayer. We will buffer 10 seconds of audio and start playing that audio while the rest of the audio loads in the background. We store the streamed audio locally so you could cache it on device for later use or simply let it be garbage collected.

Here’s the source code for those that just want to jump in. You’ll also notice code for the other tutorials as I didn’t have time to strip them out.

Here are a few screenshots of what we’ll be creating:

Tutorial #3 results screenshots

Basic Layout

The tutorial consists of just two classes:

Tutorial3: Contains the UI layout and process button clicks
StreamingMediaPlayer: Connects to the server, downloads audio into the buffer, and controls the functionality to ensure the audio continues to play seamlessly.

We’ll assume you know about UI layout using Android’s XML resource files and will instead jump right into the audio streaming code.

Start Your Streaming

Upon clicking the “Start Streaming” button, Tutorial3 creates an instance of StreamingMediaPlayer.

new StreamingMediaPlayer(textStreamed, playButton, streamButton,progressBar);

All UI elements are passed to StreamingMediaPlayer so it can perform UI update itself. In a more robust implementation, StreamingMediaPlayer would fire relevant update events and Tutorial3 would handle the UI updates. For simplicity & cleaner code in this tutorial however, StreamingMediaPlayer will be directly updating the UI.

Tutorial3 then calls StreamingMediaPlayer.startStreaming():

audioStreamer.startStreaming(“http://www.pocketjourney.com/audio.mp3″,1444, 180);

Three variables are passed to startStreaming(): a url for the media to stream (link to an .mp3 file in this tutorial), the length in kilobytes of the media file, and the lenght in seconds of the media file. These last two values will be used when updating the progress bar.

AudioStreamer.startStreaming() creates a new thread for streaming the content so we can immediately return control back to the user interface.

public void startStreaming(final String mediaUrl, long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {

this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;

Runnable r = new Runnable() {

public void run() {

try {

downloadAudioIncrement(mediaUrl);

} catch (IOException e) {

Log.e(getClass().getName(), “Initialization error for fileUrl=” + mediaUrl, e);
return;

}

}

};
new Thread(r).start();

}

Incremental Media Download

This is where the magic happens as we download media content from the the url stream until we have enough content buffered to start the MediaPlayer. We then let the MediaPlayer play in the background while we download the remaining audio. If the MediaPlayer reaches the end of the buffered audio, then we transfer any newly downloaded audio to the MediaPlayer and let it start playing again.

Things get a little tricky here because:

(a) The MediaPlayer seems to lock the file so we can’t simply append our content to the existing file.
(b) Pausing the MediaPlayer to load the new content takes awhile so we only want to interrupt it when absolutely necessary.
(c) Accessing the MediaPlayer from a separate thread causes it to crash.

So with those caveats in mind, here’s the method that bufferes the media content to a temporary file:

public void downloadAudioIncrement(String mediaUrl) throws IOException {

// First establish connection to the media provider
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {

Log.e(getClass().getName(), “Unable to create InputStream for mediaUrl:” + mediaUrl);

}

// Create the temporary file for buffering data into
downloadingMediaFile = File.createTempFile(“downloadingMedia”, “.dat”);
FileOutputStream out = new FileOutputStream(downloadingMediaFile);

// Start reading data from the URL stream
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {

int numread = stream.read(buf);
if (numread <= 0) {

// Nothing left to read so quit
break;

} else {

out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead/1000;

// Test whether we need to transfer buffered data to the MediaPlayer
testMediaBuffer();

// Update the status for ProgressBar and TextFields
fireDataLoadUpdate();

}

} while (true);

// Lastly transfer fully loaded audio to the MediaPlayer and close the InputStream
fireDataFullyLoaded();
stream.close();

}

What’s up with testMediaBuffer()?

So if you were paying attention, an important piece of functionality must reside in the testMediaBuffer() method. You’re right. That’s the method where we determine whether we need to transfer buffered data to the MediaPlayer because we have enough to start the MediaPlayer or because the MediaPlayer has already played out its previous buffer content.

Before we jump into that, please take note that interacting with a MediaPlayer on non-main UI thread can cause crashes so we always ensure we are interacting with the UI on the main-UI Thread by using a Handler when necessary. For example, we must do so in the following method because it is being called by the media streaming Thread.

private void testMediaBuffer() {

// We’ll place our following code into a Runnable so the Handler can call it for running
// on the main UI thread

Runnable updater = new Runnable() {

public void run() {

if (mediaPlayer == null) {

// The MediaPlayer has not yet been created so see if we have
// the minimum buffered data yet.
// For our purposes, we take the minimum buffered requirement to be:
// INTIAL_KB_BUFFER = 96*10/8;//assume 96kbps*10secs/8bits per byte

if ( totalKbRead >= INTIAL_KB_BUFFER) {

try {

// We have enough buffered content so start the MediaPlayer
startMediaPlayer(bufferedFile);

} catch (Exception e) {

Log.e(getClass().getName(), “Error copying buffered conent.”, e);

}

}

} else if ( mediaPlayer.getDuration() – mediaPlayer.getCurrentPosition() <= 1000 ){

// The MediaPlayer has been started and has reached the end of its buffered
// content. We test for < 1second of data (i.e. 1000ms) because the media
// player will often stop when there are still a few milliseconds of data left to play

transferBufferToMediaPlayer();

}

}

};
handler.post(updater);

}

Starting the MediaPlayer with Initial Content Buffer

Starting the MediaPlayer is very straightforward now. We simply copy all the currently buffered content
into a new Ffile and start the MediaPlayer with it.

private void startMediaPlayer(File bufferedFile) {

try {

File bufferedFile = File.createTempFile(“playingMedia”, “.dat”);
FileUtils.copyFile(downloadingMediaFile,bufferedFile);
} catch (IOException e) {

mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());
mediaPlayer.prepare();
fireDataPreloadComplete();

Log.e(getClass().getName(), “Error initializing the MediaPlaer.”, e);
return;

}

}

Transferring Buffered Content to a MediaPlayer That is Already Playing

This is a little trickier but not much. We simply pause the MediaPlayer if it was playing (i.e. the user had not pressed pause), copy over the currently downloaded media content (which may be all of it by now) and then restart the MediaPlayer if it was previously running or had hit the end of its buffer due to a slow network.

private void transferBufferToMediaPlayer() {

try {

// Determine if we need to restart the player after transferring data (e.g. perhaps the user
// pressed pause) & also store the current audio position so we can reset it later.

boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();

// Copy the current buffer file as we can’t download content into the same file that
// the MediaPlayer is reading from.

File bufferedFile = File.createTempFile(“playingMedia”, “.dat”);
FileUtils.copyFile(downloadingMediaFile,bufferedFile);

// Create a new MediaPlayer. We’ve tried reusing them but that seems to result in
// more system crashes than simply creating new ones.

mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());
mediaPlayer.prepare();
mediaPlayer.seekTo(curPosition);

// Restart if at end of prior beuffered content or mediaPlayer was previously playing.
// NOTE: We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play

boolean atEndOfFile = mediaPlayer.getDuration() – mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile){

mediaPlayer.start();

}

}catch (Exception e) {

Log.e(getClass().getName(), “Error updating to newly loaded content.”, e);

}

}

Conclusion

To get the real feel for how your audio will download, make sure to set it to a slower network speed. I recommend setting to AT&T’s EDGE network setting as it should give a lower limit on expected performance. You can make these setting’s easy in Eclipse by setting going into your Run or Debug setting’s dialog and making these selections.

EDGE settings in Eclipse

Well that’s it. I’ve inluded additional code for handling the ProgressBar and TextField updates but that should all be sufficiently easy to understand once you understand the rest of the code. Good luck during the next week as you finish your Android Challenge submissions.

And of course, here’s the source code. Please post a comment below if I need to explain anything in more detail. You’ll also notice code for the other tutorials as I didn’t have time to strip them out.

Other Tutorials

Tutorial 1: Transparent Panel (Linear Layout) On MapView (Google Map)
Tutorial 2: “Hit” testing on a View (MapView)
Tutorial 4.1: Image and Text-Only Buttons

Tagged with →  
Share →

311 Responses to Android Tutorial 3: Custom Progressive Audio Streaming with MediaPlayer

  1. Subha says:

    too useful and very good

    • Richard N. says:

      HOLY CRAP! It worked! With my first execution within my own app that I’m writing it worked. It hiccuped a bit, but it worked great in my ICS native app.

  2. [...] Transparent Panel (Linear Layout) On MapView (Google Map) 2. “Hit” testing on a View (MapView) 3. Custom Media Streaming with MediaPlayer Possibly related posts: (automatically generated)Tutorial 1: Transparent Panel (Linear Layout) On [...]

  3. [...] Tutorial 1: Transparent Panel (Linear Layout) On MapView (Google Map) Tutorial 2: “Hit” testing on a View (MapView) Tutorial 3: Custom Media Streaming with MediaPlayer [...]

  4. Marielisa says:

    Hi, great tutorial!. I’m working on a media player and i used it as a guide. I’m traying to add a funtionality, when i press a button i would like to change to the next song. It start play the music ok but after listening a few songs or after a while the emulator crash, it restart by itself, i don’t know whath i going on. I really appreciate your help. Thanks

    • Janardhanan says:

      @Marielisa

      To avoid emulator closing try deleting the old buffered file before it start to stream the song. I just give u a rough code.make it better for ur app..

      for(int i=0;i<20;i++)
      {
      File oldBufferedFile = new File(context.getCacheDir(),
      "playingMedia" + i + ".dat");

      if(oldBufferedFile.exists())
      {
      System.out.println("File Deleted "+i);
      oldBufferedFile.delete();

      }
      }

    • sagy says:

      Hi,
      could you tell me how does pv player comes into picture while creating a media player application.

  5. Michal says:

    Hello, unfortunately I have the same problem as Marielisa, after launching several songs the emulator crashes, any suggests?

  6. biosopher says:

    Hi Michal,

    We’ve been discussing this issue on another thread at AndDev.org. Here’s the link: http://www.anddev.org/viewtopic.php?p=6658#6658

    Since this tutorial was posted, I’ve further developed my streaming player to support caching of files and have been able to play unlimited numbers of files without crashing. So…I at minimum know it’s possible and not a limitation of the Android SDK. That said, it took me a week of coding and debugging to resolve various quirks of reimplementing this tutorial as a Service.

    Part of the Service challenge was dealing with multi-threaded conflicts and the caching though.

    Are you using the StreamingMediaPlayer exactly as I had released it but with ability to play more files or have you re-implemented it as a Service?

    Biosopher

  7. biosopher says:

    Actually here’s a link to the exact starting post: http://www.anddev.org/viewtopic.php?p=8255#8255

  8. Souvik says:

    Hi All,

    I am new in Android.
    Wants to develop one streaming media player application.
    This tutorial is really nice to read and implement.

    I have downloaded this source code. but not able to run it .
    Can u all please help me .

    Just show me the process how i should open this project in android to run this application!

    Thanks in advance.

    thanks.
    Souvik

  9. Biosopher says:

    Hi Souvik,

    Here’s how to import an .apk file into Android.

    1) Start a new Emulator.exe or quit out of any apps running in a current Emulator by clicking the home button.

    2) Run: adb install myproject/bin/.apk

    e.g. adb install D:personalWorkCodeEclipseMobileJourneybinMobileJourney.apk

    3) Note: Installation of new applications may require restarting the Emulator.exe as the Android app manager may only reads manifests on start.

    Cheers,
    Anthony

  10. Souvik says:

    Hi Anthony,

    Thanks for your quick reply.
    But where and how to run “Run: adb install myproject/bin/.apk”
    Where should i write this command.

    And Even if I able to run this application in emulator, can i add it as a project and
    do some modification into this? if yes, then how?

    Waiting for your reply.

    Thanks,
    Souvik

  11. Souvik says:

    Hi Anthony,

    I forget to mention that I am using windows XP.

    souvik

  12. Souvik says:

    Hi Anthony,

    Thanks a lot for your help.
    Actually I was using windows pc. And there is no need to run
    Run: adb install myproject/bin/.apk

    we can directly load the project in eclips with the same folder name .and we have to run this application. Its working properly

    Its really great.

    Thanks,
    Souvik

  13. lordhong says:

    you guys ROCK! thanks for sharing!!!

  14. Souvik says:

    Hi ,

    I have done some basic application with android.And all are independent application.
    Now I want to do something different …..

    For example, I have two separate application like tutorials & Browser/Game

    Now, what i have to do, If I wants to Launch game or Browser application by clicking Tutorial1 button which is a separate application???

    Need help..(Its like calling one application from another application)

    Thanks in advance.

    Thanks,
    Souvik

  15. Biosopher says:

    Hi Souvik,

    Applications are simply groups of Activity & Service classes. To launch one application from another, all you’ll need do is have an Activity in one Application launch an Activity from the other application.

    public class Application1 extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.main);

    Button launchApp2Button = (Button) findViewById(R.id.button_view_launch_app_2);
    launchApp2Button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
    startActivity(new Intent(this, Application2.class));
    }});
    }
    }

  16. Souvik says:

    Hi,

    I’m not able to write blogs, after clicking submit buuton it’s displaying “discard” message.

    What i have to do for this? Please let me know.

    Thanks,
    Souvik

  17. Souvik says:

    Hi Biosopher,

    Thanks for the response…
    But my scenario is little different.
    I have not done any main.xml changes for UI. like:

    public class PikuTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    TextView tv = new TextView(this);
    tv.setText(“test ===n”);
    setContentView(tv);
    }

    continued in next blog ….

  18. Souvik says:

    I have created one menu iten with submenu like:

    public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    SubMenu subITEM = menu.addSubMenu(0,0,”TEST”);
    subITEM .add(0, 1, “CM1″);
    subITEM .add(0, 2, “CM2″);
    subITEM .add(0, 3, “CM3″);
    return true;
    }

    continued in next blog …

  19. Souvik says:

    and i am handling these menu item in the function onOptionsItemSelected as switch statement where it displays through showAlert(“Menu Item Clicked”,0, “CM1″, “ok”, null, false, null);

    continued in next blog ….

  20. Souvik says:

    Now my question is when I am clicking CM1, How should i launch browser application.
    Can u please modify the code to make me understand!!

    Thanks,
    Souvik

  21. Biosopher says:

    Hello souvik,

    In the case of launching a browser window, you should pass a URI to startActivity() with an ACTION_VIEW intent. Android will then determine what the default browser is and hand your URI to it for display.

    Activity parentActivity;
    public HelpMenuHandler(Activity parentActivity) {
    this.parentActivity = parentActivity;
    }

    Then when requested, simply call the following method with your desired URL:

    parentActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(“http://www.pocketjourney.com/mobileHelp.do”)));

    Cheers,
    Biosopher

  22. Souvik says:

    Hi Biosopher,
    Thanks for the response…Its working with some small changes.
    However we are calling Uri API, and its launching browser with the mentioned link.

    But what happen if, I want to launch one of my own application by clicking the menu item?
    suppose I want to launch “app1″ by clicking one menu item from “app2″. Then what activity I have to start?

    Thanks,
    Souvik

  23. Biosopher says:

    Hi Souvik,

    Simply call: startActivity(new Intent(this, YourActivity.class));

  24. Souvik says:

    Hello Biosopher,

    But I am not able to call like this:
    “Tutorials” is one different application for me. but this stsrtActivity I am calling from “TestApp”.
    Where Tutorial and TestApp both have different package name. then how should I call ?

    startActivity(new Intent(this, Tutorials.class));

    For me if i call like this , its giving me error: Tutorials cannot be resolved to a type

    Thanks,
    Souvik

  25. Souvik says:

    Hi,
    How to refresh R.java file if its not updating automatically when I am adding one file in resource?

    Thanks,
    Souvik

  26. Biosopher says:

    Hi Souvik,

    Make sure you are reading all the error messages in detail.

    You are not allowed to have capital letters in your resources files so ‘HALUDPAKHI’ is an invalid file name. Change it to lower case.

    The R.java should refresh itself but you can always right click on your project in Eclipse & select “Refresh” if necessary.

    Anthony

  27. Souvik says:

    Thanks,
    I solved the problem.
    Actually R.java file is not updated automatically because there is one “Thub.db” file inside “res”.
    When i remove this file form that folder is updated automatically.

    Now I can able to play mp3 file from resource.
    But need help in case of playing from URl.
    Have tried this steps, but not working:

    try
    {
    MediaPlayer mp1 = new MediaPlayer();
    mp1.setDataSource(“http://ip address /Jingle_Bell-Dog.mp3″);
    mp1.start();
    }
    catch ( IOException e )
    {
    Log.e( “ioexception”, “”, e);
    }

    But its not playing .
    Any suggestion??
    Thanks,
    Souvik

  28. [...] 2: “Hit” testing on a View (MapView) Tutorial 3: Custom Media Streaming with MediaPlayer Tutorial 4.1: Image and Text-Only Buttons Possibly related posts: (automatically [...]

  29. Anu says:

    Hi,

    I was wondering if you could provide a sample code of how u created the media player as a service?

    thanks!
    anu

  30. ele says:

    Hi,

    FileUtils were supported in the earlier version .but not in 1.0
    how to solve this problem?

    thanks

  31. Biosopher says:

    Hello Ele,

    It seems we now need to write the code ourselves in order to copy files. Here’s the code for doing so. Hopefully I’ll get the time to rewrite and update this blog posting soon.

    Anthony

    public static void moveFile(File oldLocation, File newLocation)
    throws IOException {

    if ( oldLocation.exists( )) {

    makeDirectories(newLocation, false);

    //BufferedReader reader = new BufferedReader( new FileReader( oldLocation ) );
    //BufferedWriter newFWriter = new BufferedWriter( new FileWriter( newLocation, false ) );

    BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
    BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
    try {
    byte[] buff = new byte[8192];
    int numChars;
    while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
    writer.write( buff, 0, numChars );
    }
    } catch( IOException ex ) {
    throw new IOException(“IOException when transferring ” + oldLocation.getPath() + ” to ” + newLocation.getPath());
    } finally {
    try {
    if ( reader != null ){
    writer.close();
    reader.close();
    }
    } catch( IOException ex ){
    Log.e(“FileUtils”,”Error closing files when transferring ” + oldLocation.getPath() + ” to ” + newLocation.getPath() );
    }
    }
    } else {
    throw new IOException(“Old location does not exist when transferring ” + oldLocation.getPath() + ” to ” + newLocation.getPath() );
    }
    }

  32. Guru says:

    When the streaming is happening , at one of the cursor position the Media players gets paused with throwing this error.

    11-19 16:00:06.659: ERROR/MediaPlayer(536): Error (-38,0)

    Whats the reason for this error??

  33. Guru says:

    oh let me correct the error that i get when i run tutorial 3

    11-19 20:09:41.339: ERROR/Player(247): 124584
    11-19 20:09:41.350: ERROR/Player(247): /data/data/com.pocketjourney.tutorials/cache/playingMedia1.dat
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): Error initializing the MediaPlaer.
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): java.io.IOException: Prepare failed.: status=0xFFFFFFFC
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at android.media.MediaPlayer.prepare(Native Method)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at com.pocketjourney.media.StreamingMediaPlayer.startMediaPlayer(StreamingMediaPlayer.java:170)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at com.pocketjourney.media.StreamingMediaPlayer.access$2(StreamingMediaPlayer.java:159)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at com.pocketjourney.media.StreamingMediaPlayer$2.run(StreamingMediaPlayer.java:143)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at android.os.Handler.handleCallback(Handler.java:542)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at android.os.Handler.dispatchMessage(Handler.java:86)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at android.os.Looper.loop(Looper.java:123)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at android.app.ActivityThread.main(ActivityThread.java:3742)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at java.lang.reflect.Method.invokeNative(Native Method)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at java.lang.reflect.Method.invoke(Method.java:515)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497)
    11-19 20:09:41.430: ERROR/com.pocketjourney.media.StreamingMediaPlayer(247): at dalvik.system.NativeStart.main(Native Method)

  34. Polox says:

    Guru, I had the same issue then tried to play wrong content via Media Player. Since you cannot(as I see in SDK) specify content-type for sound file Media Player try to open and play .dat file and looks like cannot do so. Currently android supports olsy MPEG-4, MP3, AAC, AMR, JPG, PNG and h.264 formats.

    p.s
    I could be wrong of course but it is my observarions

  35. Breno says:

    Hey Biosopher

    Nice Tutorial, congratulations!! I’ve downloaded here, with SDK 1.0, and no problem to compile. But, when running, an error in LogCat happens: java.net.UnknownHostException: Host is unresolved: http://www.pocketjourney.com:80. The link is there, i tried to download in browser, no problem. But i don’t know why this happens. I’m on a proxy, and i’m using proxy settings on Emulator, and i can access internet on it without problem. Do you have any idea? thanks a lot

  36. Breno says:

    i missed to say the rest of error: at java.net.Socket.connect(Socket.java:928)

  37. villain_dm says:

    Gyru:

    player cannot read user’s files.

    use:

    FileInputStream ins = new FileInputStream(bufferedFile.getAbsolutePath());
    mediaPlayer.setDataSource(ins.getFD());

    instead

  38. cmavr8 says:

    Hi guys, that is a nice tutorial.
    I don’t think it’s clever if each one of us started their own program to use this.

    So, has anyone written a working program that can stream audio?
    If not, do we have a common project? Should we start one?

    Thanks,
    Chris

  39. lym says:

    Thanks for sharing your code, it’s a nice tutorial.
    But when I run in in Android 1.0 SDK, the startMediaPlayer() throws exception when calling mediaPalyer.prepare(), if I change the data source to a local mp3 file, it can works.

    private void startMediaPlayer() {
    try {
    File bufferedFile = new File(context.getCacheDir(),”playingMedia” + (counter++) + “.dat”);
    moveFile(downloadingMediaFile,bufferedFile);

    mediaPlayer = new MediaPlayer();
    // the following line cause prepare throws io exception, don’t know why …
    // mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());

    // change data source to local file, it works
    mediaPlayer.setDataSource(“/sdcard/Toto_-_Africa.mp3″);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.prepare();

    I have no idea why the bufferefFile cannot be used in mediaPlayer. can you help ?

  40. r0ckf3l3r says:

    Hi,

    First of all, nice tutorials you have here.

    I’ve been trying to play your file. I configured the app, loaded it with Eclipse, and installed it. When I try the Tutorial 3 application, however, I can stream whatever file I want, but I don’t have any sound at all..

    Still, there’s no problem with it, or so says Eclipse.

    ty,

    r0ckf3l3r

  41. villain_dm says:

    cmavr8

    if you are intrested in common app – android platform has build in streaming activity in Media.apk

    just use corresponding intent to invoke it:

    this activity uses MediaPlaybackService to play the file. You can also use it.

    MusicUtils.bindToService(this, new ServiceConnection() {
    public void onServiceConnected(ComponentName classname, IBinder obj) {
    try {
    IntentFilter f = new IntentFilter();
    f.addAction(MediaPlaybackService.ASYNC_OPEN_COMPLETE);
    registerReceiver(mStatusListener, new IntentFilter(f));
    MusicUtils.sService.openfileAsync(getIntent().getData().toString());
    } catch (RemoteException ex) {
    }
    }

    public void onServiceDisconnected(ComponentName classname) {
    }
    });

  42. villain_dm says:

    cannot post xml:-) sry

    activity android:name=”StreamStarter” android:theme=”@android:style/Theme.Dialog”
    intent-filter
    action android:name=”android.intent.action.VIEW” />
    category android:name=”android.intent.category.DEFAULT” />
    category android:name=”android.intent.category.BROWSABLE” />
    data android:scheme=”http” />
    data android:mimeType=”audio/mp3″/>
    data android:mimeType=”audio/x-mp3″/>
    data android:mimeType=”audio/mpeg”/>
    data android:mimeType=”audio/mp4″/>
    /intent-filter>
    /activity

  43. German says:

    Hi,

    I noticed that getDuration() is returning the total duration of the file (probably retrieved from the file’s header), instead of returning the total duration of the buffered file. This is causing the method transferBufferToMediaPlayer() not to be called (it is called only when the whole file is downloaded). Does anybody knows a workaround for this issue?

    Thanks

  44. incandenza says:

    Thanks for the tutorial.

    I found that you don’t actually have to copy the file over to a second one. You can just point the media player back to the same file. The only issue is that it looks at the file length when you give it the file, and then it will stop when it hits the end. So, you do have to reset it and point it back at the file again, but it can be the same one. There’s no “locking” that prevents you from appending to it.

  45. amit says:

    I get java.io.IOException : prepare failed in startMediaPlayer() until the entire file is downloaded, at which point, prepare() works.

    I am doing this to setDataSource:
    FileInputStream ins = new FileInputStream(bufferedFile.getAbsolutePath());
    mediaPlayer.setDataSource(ins.getFD());

    Any ideas?

    -amit

  46. Biosopher says:

    Hi Amit,

    I tried to send this directly but the email you provided was inaccurate.

    Could you post more of your code? It’s hard to tell with just that short snippet. Please show me the full set of calls from new MediaPlayer() through to mediaPlayer.prepare().

    Thanks,
    Anthony

  47. amit says:

    What is your email Biosopher? I will email you all my code. I am using my correct email..

    Thanks.

  48. amit says:

    After some tinkering, I was able to make the app work with the mp3 file. But my real goal is to be able to stream videos. The same logic does not seem to work with mp4 or 3gp files. Anybody have any input? Whats this MediaPlaybackService class? Anybody know of any code that plays streaming video off the net?

    amit

  49. Biosopher says:

    For simple streaming video, just follow the code for Android’s video demo in APIDemos. We use that code for streaming video without a problem.

    Anthony

  50. amit says:

    Anthony, by the APIDemo, I’m guessing you’re referring to the MediaPlayerDemo_Video class.
    Since you are using this code for streaming video without a problem, can you share the URL’s of some of the videos you are able to play? The more variety the better. And if you can tell me exactly what kind of streamable content MediaPlayer can handle, that would be great too. Thanks a lot!

  51. Biosopher says:

    Hi Amit,

    We settled on .3gp as getting other formats to stream properly was not working in the earlier versions. Other formats might work now but we’re happy with .3gp as it’s smaller than other formats and is an open format.

    I’ll send the files to you to work with.

    Anthony

  52. amit says:

    Anthony, thanks for your response. I have been able to play 3gp and mp4 files locally too. IE, if I download these files onto the device then MediaPlayer can play them. But what I want to do is to be able to play streaming/progressive download videos straight off the web, with a minimum buffer. It seems MediaPlayer cannot do this (Prepare failed error), which is why I started looking into your StreamingVideoPlayer since downloading smaller chunks at a time and playing is faster than downloading the whole file and playing.

    Are you aware of anything that can help me play streaming or progressive download video content, without downloading the whole file first?

  53. Biosopher says:

    The files I provided you are ones we stream from a server and play via Android’s MediaPlayer (i.e. we don’t download them first and then play them locally).

    Without seeing your code, it’s hard to say what’s wrong. The main bug people typically introduce when playing video’s is to not setup their SurfaceView properly. Make sure your method call chain looks something like this else you’ll get a prepare error:

    public Your MediaController()
    {

    // Add the video callback listener
    videoSurface.getHolder().addCallback(MediaController.this);


    }

    // Implementation of SurfaceHolder.Callback
    @Override
    public void surfaceCreated(SurfaceHolder videoHolder)
    {
    // Don’t create and prepare your MediaPlayer until this method has been called
    createMediaPlayer();
    }

    private void createMediaPlayer() {
    try {
    foregroundMediaPlayer = new MediaPlayer();
    foregroundMediaPlayer.setDataSource(mediaUri);
    foregroundMediaPlayer.setDisplay(videoSurface.getHolder());
    foregroundMediaPlayer.setOnCompletionListener(this);
    foregroundMediaPlayer.setOnErrorListener(this);
    foregroundMediaPlayer.setOnBufferingUpdateListener(this);
    foregroundMediaPlayer.setOnPreparedListener(this);

    // If prepare() is called before the SurfaceView is ready, you’ll get a
    // ‘preprare failed error’ when MediaPlayer accesses the invalid SurfaceView
    foregroundMediaPlayer.prepare();
    foregroundMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    }catch (Exception e) {
    Log.e(getClass().getName(), “Error while preparing MediaPlayer path: ” + mediaUri, e);
    }
    }

  54. amit says:

    Anthony, I am creating the MediaPlayer only after surfaceCreated() has been called. I am still getting prepared failed error. Here is the code (I’ve removed the empty listener methods).

    public class TestMediaPlayer2 extends Activity implements
    OnBufferingUpdateListener, OnCompletionListener,
    MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {

    private static final String TAG = “MediaPlayerDemo”;
    private int mVideoWidth;
    private int mVideoHeight;
    private MediaPlayer mMediaPlayer;
    private SurfaceView mPreview;
    private SurfaceHolder holder;

    private String videoStreamUrl;

    /**
    *
    * Called when the activity is first created.
    */
    public void onCreate(Bundle icicle) {
    Log.d(TAG, “hello”);

    super.onCreate(icicle);
    setContentView(R.layout.main);

    Toast.makeText(this, “hi”, Toast.LENGTH_SHORT);

    mPreview = (SurfaceView) findViewById(R.id.surface);
    holder = mPreview.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    //extras = getIntent().getExtras();

    videoStreamUrl = /*url to a 3gp file. pocketjourney is complaining..*/

    Log.d(TAG, videoStreamUrl);

    }

    public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    Log.d(TAG, “surfaceCreated called”);
    playVideo();
    }

    private void playVideo() {
    Log.d(TAG, “in playVideo()”);

    try {
    // Create a new media player and set the listeners
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(videoStreamUrl);
    mMediaPlayer.setDisplay(holder);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.prepare();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    } catch (Exception e) {
    Log.e(TAG, “error: ” + e.getMessage(), e);
    }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
    Log.d(TAG, “onPrepared called”);
    mVideoWidth = mMediaPlayer.getVideoWidth();
    mVideoHeight = mMediaPlayer.getVideoHeight();
    if (mVideoWidth != 0 && mVideoHeight != 0) {
    holder.setFixedSize(mVideoWidth, mVideoHeight);
    mMediaPlayer.start();
    }

    }

    }

  55. chris says:

    HI Biosopher,
    i am also interested in this 3gp links ., may you forward me them also.

    In this days i am also starting to develop me first tests for streaming and will also try your scripts.
    till now i am experimenting with the api demo, but all he 3gp i tested are not opening.

    greets
    chris

  56. chris says:

    Hi together,
    i was able now to create a 3gp that plays nice from local, but not over the net

    does anyone have a complete source example just simple streaming 3gp over the net
    with http protocol?

    thanks
    chris

  57. Biosopher says:

    The MediaPlayer streaming example in Android’s ApiDemos provides easy streaming of 3gp. I’ve used the same code by simply pointing to my .3gp file at my server.

    • Geetha says:

      Hi

      Video stream in ApiDemos is not working showing java exceprion error after mediaplayer.prepare()

      Thanks,
      Geetha

  58. chris says:

    hi Biosopher,

    thanks, I got now also a “small” 3gp File running with the API DEMO, and also with 2 other option.
    But in the moment this 3gp or .mp4 comes bigger, lets say over 2mb, it is not working.

    I have now two option working for smaller files.

    // Version 1
    mVideoView.setVideoURI(Uri.parse(urlpath));
    mVideoView.setMediaController(new MediaController(this));
    mVideoView.requestFocus();

    // Version 2
    Intent i = new Intent(Intent.ACTION_VIEW);
    Uri u = Uri.parse(urlpath);
    i.setDataAndType(u, “video/*”);
    startActivity(i);
    //for all other beginners: use setDataAndType! I search hours till i found out :)

    But as mentioned, if its bigger, lets say like my testfile: on http://www.guruk.com/3gp/2.mp4
    it stops working.

    Thats the Reason I tried to work with this Streaming Demo on this Page here.
    For now I can get mp3 downloaden and he even starts playing but stops after around 8sec. (i guess in the moment he refresh the buffer its gone)

    If you have any idea, let me know. If you send me your email, I also will provide you with all sources I have.

    The goal is a streaming functionality, like mentioned on this page for music.. to realize for videos.. also with big files.

    (second small question)
    When I understand right, the demo above loads piece by piece and appends to the pieces bevore. But so i guess a big file with lets 700 MB (video), will never work with this demo (just because internal memory of the g1)??

    Greets
    Chris

  59. Biosopher says:

    We have streamed file up to 5MB that were 5 mins long. Check the format of your files. The Android MediaPlayer is very finicky still.

    We create our .3gp using Quicktime Pro and have had no problems. However we did have numerous issues creating .3gp files with other audio tools.

    Biosopher

  60. Biosopher says:

    Chris,

    As you say, this streaming media player is for small files (1-10MB) as anything larger should probably be downloaded via a sync cable.

    As a side note, we wrote this tool when Android’s sreaming media functionality was not working well. Now, we simply use Android’s built-in streaming ability.

    Anthony

  61. ramakrishna says:

    Hii Biosopher,

    I am also trying to stream videos from a vlc server using the mediaplayerdemo_video in Apidemos.The file i have been trying to stream is of .3gp format(600 kb). But the problem is that i am not able to stream this file consistently. i mean to say that i can stream the file successfully once or twice but most of the times i get error
    as
    error: Prepare failed.: status=0xFFFFFFFF
    java.io.IOException: Prepare failed.: status=0xFFFFFFFF

    I tried to find out the error and solve but all my efforts went in vain.So could u please help me in this matter?

  62. TheiPirate says:

    Anyone have working mp3 streaming? use pastebin(google it) and link your code for us.

    Thanks

  63. kartik trivedi says:

    It is giving me exception while calling prepare() method of MediaPlayer. I am using SDK 1.1 is there problem in it. Please mail me what could be wrong in it.

  64. Amit Panwar says:

    Hi Biosopher,

    I was trying MediaPlayerDemo_Video example from API Demos.

    Used the URL for different mp4 and 3gp files but the same issue:
    I got the following exception-

    error: Prepare failed.: status=0xFFFFFFFF
    java.io.IOException: Prepare failed.: status=0xFFFFFFFF

    If API demos don’t have any issue, Please send me the URLs of some 3gp/mp4 files so that I can enable myself to test the same.

    Thanks,
    Amit

  65. Biosopher says:

    Hi Amit,

    As amit suggests, this works in API Demo’s MediaPlayerDemo_Video class:

    http://www.pocketjourney.com/downloads/pj/video/famous.3gp

    Cheers,
    Anthony

  66. Bindu Rao says:

    Hi: I liked your Tutorial3 demo. Thanks. However, I am getting an error after the music starts playing – it seems to come due to the “counter” being wrong, or not set properly, between the downloadingmedia and playing media. In particular, the error shown is:

    java.io.FileNotFoundException: / data/data/com.pocketjourney.tutorials/cache/playingMedia2.dat

    and seems to come from:
    transferBufferToMediaPlayer – line 199 (in my version of your code), where the code is as follows:
    ——–
    File bufferedFile = new File(context.getCacheDir(),”playingMedia” + (counter++) + “.dat”);
    //FileUtils.copyFile(downloadingMediaFile,bufferedFile);

    mediaPlayer = new MediaPlayer();
    //mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());
    FileInputStream ins = new FileInputStream(bufferedFile.getAbsolutePath());
    mediaPlayer.setDataSource(ins.getFD());

    ——–

    Seems like counter has become 2, when playingMedia2.dat does not exist / is not created. only playingMedia1.dat exists.

    No wonder there is a fileNotFound exception.
    Any ideas, your help will be appreciated.

    Thanks
    Bindu Rama Rao
    binduramarao@yahoo.com

  67. Senthil says:

    Hi,

    I have tried video streaming using API demo sample. it s working only for the url which is suggested by amit..

    for all other url i am getting the following error.

    error: Prepare failed.: status=0xFFFFFFFF
    java.io.IOException: Prepare failed.: status=0xFFFFFFFF

    can anyone provide me some other url of 3gp video format..?

    thanks,
    Senthil.M

  68. msenthil says:

    Hi,

    Can anyone tell me how to resolve the follwing error while implementing video streaming.

    error: Prepare failed.: status=0xFFFFFFFF
    java.io.IOException: Prepare failed.: status=0xFFFFFFFF

    i am getting this error when mediaplayer.prepare(); is called.

    thanks,
    Senthil.M

  69. Biosopher says:

    Hi msenthil,

    Your files are most likely not compatible with Android.

    Android has issues with most file formats. I’ve only been able to get .3gp to work successfully. Even then, only files created using Quicktime Pro have worked for me.

    E.g. this file was created using Quicktime Pro:
    http://www.pocketjourney.com/downloads/pj/video/famous.3gp

    If the file above works but your other ones don’t, then you need to fix the format of your file.

    Anthony

    • msenthil says:

      Hi Anthony,

      Thanks for your reply. I understood that the problem is with the URL which i tried. When i try to play that url, i got a message “Sorry ,this video is not valid for streaming to this device”

      thanks,
      Senthil.M

  70. Senthil says:

    Hi friends,

    Can anyone temme how to change the colour of the stars in rating bar in android.

    I am getting the stars in green colour when we rate them.

    But i need to change them as some other colour when we rate.

    Is it possible..?

    thanks ,
    Senthil

  71. Biosopher says:

    Hi Senthil,

    I’m not doing Android dev at the moment so my info may be slightly out of date, but here’s what I know:

    A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in stars.

    The XML format for updating the ProgressBar was a combination of this:

    Where ‘shape_media_segment_rating_bar’ was defined as such:

    More info here:
    http://developer.android.com/reference/android/widget/RatingBar.html

    These pages offer info on changing the ProgressBar style though not the RatingBar stars (hope it helps):
    http://groups.google.com/group/android-developers/browse_thread/thread/147e60581e7626b3
    http://www.anddev.org/seekbar_progressbar_customizing-t6083.html

    Cheers,
    Anthony

  72. ivy says:

    hi.. i’ve been studying your code and the tutorial and i found some inconsistencies between the two.. plus when i run the emulator using either from the downloaded code and the code from the tutorial, adb logcat gives me an error about media player prepare failed.. can you help me?

  73. Aahna says:

    Hi,
    Can anyone tell me how to stream live videos on android emulator?
    Kindly help as this is very urgent!!!
    REgards,
    Aahan

  74. Aahna says:

    Hi,
    Can anyone tell me how to stream live videos on android emulator?
    Kindly help as this is very urgent!!! Mail me available info or your knowledge on this requirement on chiragpayal@gmail.com
    REgards,
    Aahna

  75. Biosopher says:

    Hi Aahna,

    Use the MediaPlayerDemo_Video example in Android’s APIDemo. Simply set the example’s ‘path’ argument to the url of your video file. I highly recommend getting your file to load from the local directory first so you can ensure your media file is in a valid format.

    Cheers,
    Anthony

    • Aahna says:

      Hi Anthony,
      Thanks for your reply. However I am able to play only only pocketjourney link given on this webpage by Amit which ofcourse is not live link.
      I tried to put some http links from some live news channel weblinks but all the times emulator shows error message, “Sorry, this video can not be played”.
      I am using windows Vista system and android 1.5 with ADT 0.9 version and testing on APIDemo, MediaPlayerDemo_Video example only.
      If possible, can you send me some live video weblinks which plays successfully on emulator by streaming online video?

      REgards,
      Aahna

  76. Biosopher says:

    Android does not handle media files very well. They MUST be in one of the few supported formats. E.g. this URL points to a media file that was encoded properly for the .3gp format using QuickTime:

    http://www.pocketjourney.com/downloads/pj/video/famous.3gp

    I highly recommend using QuickTime to format your media files. Ensure you test any media format by playing through Android off the local drive before trying to play those files off the net.

    I don’t know of any specific ‘live’ URLs that play well through Android.

    Anthony

    • Aahna says:

      Dear Anthony,
      Thanks for your quick response. However, I am not able to find any online .3GP links. All 3gp/mp4 videos are found on .html URL link only :(
      It would be great if you can elaborate more on encoding part. As far as I know we can use quicktime or VLC player and stream/encode to any other format. However, I am not able to choose particular .3GP or .MP4 video links for this job.
      Can you or anyone else help me?
      Regards,
      Aahna

  77. Biosopher says:

    Hi Aahna,

    If you are streaming other people’s media files (i.e. you can’t encode them to .3gp/.mp4 yourself), then you’ll need to parse through that sites .html to find the media file links to pass to Android.

    What website’s media files are you trying to stream to Android?

    Anthony

  78. YuvalKesten says:

    Dear Anthony – Thanks for all!
    I am developing an app requiring “streaming” (PD…) and this post is the only place on the web I found the solution.
    I am using QuickTimePro for images I have downloaded from YouTube (With the uploader permission…) and it’s working great!

    Thanks!!!

    • Aahna says:

      Hi Anthony,

      Can you explain me your reply with easy to understand steps to meet my requirement?
      ” Anthony — If you are streaming other people’s media files (i.e. you can’t encode them to .3gp/.mp4 yourself), then you’ll need to parse through that sites .html to find the media file links to pass to Android.”

      I am interested in streaming and getting played some live videos on android emulator 1.5 for example,
      http://www.ndtv.com/news/videos/video_live.php?id=LIVE_BG24x7

      So, how should I achieve this successfully? Your procedural response would help many developers like me as there is no clear response to this question on any forum.
      Let me know wihtout RTSP support on emulator 1.5, would this be possible to stream live news/sport videos?

      Regards,
      Aahna

    • Aahna says:

      Hi YuvalKesten,
      You have mentioned that you are using quickTimePro for images downloaded from youTube. Can you tell me what are the exact steps you are performing to get streamed videos?

      I tried using VLC network stream to get some URL link as an input and putting encoded streamed out HTTP/UDP packets on my own system and then redirecting packets from desktop to emulator’s IP. But it failed :( Because of this, I am not able to play any other .3gp video link except that pocketjourney link.

      Your or anybody’s reply on this would be great help.
      Thanks,
      Aahna

  79. Biosopher says:

    Hi Aahna,

    I’m streaming my own videos accessible from my own server. Streaming other people’s videos is typically against their usage agreement. If you have authorization though, then someone on their IT team can help you access the videos.

    If you want to stream videos from another site though, you would need to parse through their HTML & Javascript to find their video file links. Nowadays though, most companies encode their video links so you wouldn’t be able to access them even if you tried.

    I don’t know the answer to your RTSP question.

    Anthony

    • Aahna says:

      Hi Anthony,
      Thanks for the explanation. I would have to find such sites for getting live streaming. Kindly keep me updated if you find any such site who can authorize us to get their live videos streamed.

      Can you answer me the above question I have put to YuvalKesten?
      Putting it othe way, would like to ask how you are achieving formatting the video through quick time and getting it played on emulator? Is the procedue I have mentioned above is correct?
      Because with my encoded packets I am able to playback on another instance of VLC (in your case might be quicktime) but those are not getting redirected to emulator.
      How to achieve that?

      Regards,
      Aahna

  80. Nicolas says:

    Hi Anthony,

    I just have a question about your tutorial3. I tried to play an online radio (with this URL for example http://scfire-ntc-aa03.stream.aol.com:80/stream/1003) and it’s not working. Is your tutorial working only for mp3s ? In that case, isn’t it possible to listen streaming music coming from an streaming radio ?

    Thanks.

    Nicolas

  81. Biosopher says:

    Hi Nicolas,

    The answer to your question has been discussed many times in other posts for this tutorial.

    In short, Android does not handle media files very well. They MUST be in one of the few supported formats. E.g. this URL points to a media file that was encoded properly for the .3gp format using QuickTime:

    http://www.pocketjourney.com/downloads/pj/video/famous.3gp

    I highly recommend using QuickTime to format your media files. Ensure you test any media format by playing through Android off the local drive (using the API Demo example) before trying to play those files off the net.

    In your case, download the file from AOL and ensure that Android can play their specific format.

    Anthony

    • Nicolas says:

      Hi Anthony,

      I’m sorry if I haven’t been really clear but I was talking about audio and not video. I tried MP3 and OGG web radios but not working. Android can handle these both formats for one file right ? So it shouldn’t be impossible to read the same formats from a stream ?

      Thanks again for your time :)

      Nicolas

  82. Biosopher says:

    Hi Nicolas,

    Why aren’t you just streaming using Android’s built-in streaming capability? All you need do is put a URL as the path for the MediaPlayer example in ApiDemo.

    Doesn’t that work for you?

    Anthony

  83. Biosopher says:

    Hi Aahna,

    Two answers:

    1) Go here for video files you can stream. They have numerous files you can download:
    http://mediaplayer.group.cam.ac.uk/component/option,com_mediadb/itemid,26

    2) It’s very easy to create a streamable .3gp file using QuickTime Pro. Simply open your video in QuickTime Pro and then choose ‘Export’ and select .3gp.

    Anthony

    • Aahna says:

      Hi Anthony,
      Thank you very much for your support so far. I hardly seen anyone helping developers like this!!! You are really great having lot of patience and clarity on your inputs.

      Adding another requirement to my application, I need to let user enter some URL video link to play the streamable video. If this URL lists the available video items then how to decide at run time whether android can play selected video on emulator :(

      Also I am not using Linux. I am using windows vista, android 1.5, ADT 0.9.

      Regards,
      Aahna

      • YuvalKesten says:

        Hi,
        I am working on an Android project as part of a university project. I am working with some film-makers from the Arts faculty.
        What we are doing is – they are uploading their movies to youtube, I am downloading them, convert them using QucikTimePro (Export to IPhone(Cell)) and then I upload the converted videos to a file server.
        Hope I helped…

  84. Biosopher says:

    Hi Nicolas,

    Yes…this tutorial only works with MP3 files. Radio and other audio streaming sites are not typically streaming mp3 files as their feeds are continuous while mp3 files are discreet chunks (with headers and footers in the file describing start and end information).

    Anthony

  85. ivy says:

    Hi. I’m developing an application that can stream from internet radio stations. Can you help me out? THanks

  86. Biosopher says:

    Hi Ivy,

    Sadly my code doesn’t work for internet radio stations as they don’t typically use streams compatible with Android’s media player (that I know of).

    Cheers,
    Anthony

  87. Senthil says:

    Hi Anthony,

    Can we able to encode the video file url through code to make it to support streaming in android…?

    thanks,
    Senthil

  88. Biosopher says:

    Hi Senthil,

    You definitely couldn’t convert streaming video in the wrong format to the correct format. You’d have to download the entire file and then convert it. Of course, you would then need access to Java code that could convert whatever format the server is providing into a format that Android accepts (e.g. .3gp). Most likely it would be impossible or a LOT of work though.

    Anthony

  89. Biosopher says:

    Hi Tiger,

    This tutorial uses Android’s MediaPlayer so it would work with any format supported by Android.

    Anthony

  90. Biosopher says:

    Hi Senthil,

    I’m sure there are but I found that Quicktime Pro worked and stooped looking after that.

    Anthony

    • Senthil says:

      Hi Anthony,

      Actually for my application, i am getting the video urls dynamically from the server.. and those video files are not supported for streaming in android device. I need to convert those urls to proper format so that it supports streaming in android. currently i am downloading the entire video in SD card and playing it. but i don want the user to wait until the entire video is getting downloaded. I don think that quicktimepro is helpful for my case. Also i am searching for any java code available for video streaming. if i get any information, it ll be very helpful.

      thanks,
      Senthil.M

      • Senthil says:

        Hi Anthony,

        Can you please tell me whether quicktimepro will help for the above scenario i mentioned or any other way if you found for streaming, please post here.

        thanks,
        Senthil.M

      • Biosopher says:

        Converting video ‘on the fly’ is not possible from what I know…or at least too difficult to attempt unless you’re a media format guru. Your current approach is the only solution…though not very usable as you say.

        Anthony

  91. Tiger says:

    Hi,
    I have been looking osmewhat in the code and I noticed that the call to startStreaming actually needs a file length and the duration… Let’s say that I’d like to stream an infinite file, a real stream… Has that been implemented, so could I pass like for example a -1 as argument for both ?

  92. Biosopher says:

    Hi Tiger,

    You could easily implement that update. The file length is only really used for displaying the playback progress. E.g. 1:01 mins played of 5:00 total mins.

  93. Senthil says:

    Thanks for your reply Anthony..

    Senthil.M

  94. theluk says:

    why dont you use audiotrack??? there you can easily write data to it, while its playing…

    • Biosopher says:

      Thanks for pointing us to AudioTrack, theluk. That class wasn’t available when I wrote this tutorial. It won’t help Senthil’s audio format translation but might provide a useful extension to this tutorial’s solution.

      Sadly as with most of Android’s code, there’s very little in the way of documentation. Here’s a brief from a post by Ed Burnette:

      AudioTrack and AudioRecord are interesting to low level audio developers:

      * Expose raw PCM audio streams to applications
      * AudioTrack: Write PCM audio directly to mixer engine
      * AudioRecord: Read PCM audio directly from mic
      * Callback mechanism for threaded application
      * Static buffer for playing sound effects

      Full post: http://blogs.zdnet.com/Burnette/?p=1133

      Anthony

  95. Uma Maheswara Rao says:

    hi friends

    i have been working on a problem called out of memory exception.

    i am getting this exception in my application when i spawn more number of threads.

    i am using

    System.gc();
    runtime.gc();

    in onDestroy method. Still i am getting this exception..

    Can anyone knows the solution for this problem…?

    thanks,
    Uma Maheswara Rao

  96. Jason says:

    Anthony,
    Thanks for your blog post and code. I came across it only after writing something very similar. Glad to see I (mostly) had it right!
    Jason

  97. [...] to work just fine). We use the methode described here for good buffered playback from socket : http://blog.pocketjourney.com/2008/04/04/tutorial-custom-media-streaming-for-androids-mediaplayer/ (so the inputstream is not from an URL but from our native socket and we don’t play .mp3 but [...]

  98. [...] We have been making some progress though. At the moment we are able to stream speex-encoded audio to the device, decode it (this step is very slow on emulator, but fast enough on the device itself) and play it as a .wav file (putting a dummy wav-header before the actual data seems to work just fine). We use the methode described here for good buffered playback from socket : http://blog.pocketjourney.com/2008/04/04/tutorial-custom-media-streaming-for-androids-mediaplayer/ [...]

  99. Senthil.M says:

    Hi Anthony,

    I have one more question regarding the videos. Actually i am calling an intent after the video is getting played completely by using setoncompletionlistener method. When i try to play video in media player of android, for some videos it is not calling the setoncompletionlistener method when the video is finished. Simply video playing time (displayed on the left side of media player)is getting increased infinitely even after the whole playing time (displayed on the right side of media player) of video. I dont know the reason why it is happening like that.. This scenario is occurring especially when we drag the video fully.

    regards,
    Senthil.M

  100. Biosopher says:

    Hi Senthil,

    Sounds like a possible bug. I’d try posting in the Android dev group to see if a Google/Android lead knows a solution or if it’s a bug.

    Anthony

    • Senthil.M says:

      Hi Anthony,

      Thanks for the reply. If you found any solution for this problem, please post the information here so that it will be helpful for everyone.

      thanks,
      Senthil.M

  101. alwaystry says:

    Hi Biosopher,

    thanks for the tutorial!

    I try the code to run on the HTC G1, but ist seemed something wrong.

    private void fireDataPreloadComplete() {
    Runnable updater = new Runnable() {
    public void run() {

    mediaPlayer.start();//never be called

    startPlayProgressUpdater();
    playButton.setEnabled(true);
    // streamButton.setEnabled(false);
    }
    };
    handler.post(updater);
    }

    the line “mediaPlayer.start()” is apparently never be called, so i can hear nothing.

    Do u have some ideas?

    thanks
    T.B

  102. Biosopher says:

    Hi alwaystry,

    Sadly I’m not developing on Android at the moment. Probably a threading issue or your not preparing the MediaPlayer properly.

    The code worked in prior versions so perhaps the newest release broke the code.

    Anthony

  103. Yen says:

    Hi Anthony,

    First of all, Thanks a ton for the tutorial.

    I downloaded the tutorial and created a new project with the same files.

    I compiled the project and was able to run it without any errors. I used the URL provided in the example.

    Also, in the emulator I could see the buffering taking place. However, No sound is coming .
    I am using Windows vista and Android SDK 1.5 with Eclipse.

    I think, when i call mediaplayer.prepare () , it throws an exception – ‘ Error Not Supported’.

    I also tried with Local files. it worked.. So does it mean the file format in the URL ( provided in the example ) is not supported..?

    If yes .. how to go about it .. please explain.. I am new to Android..

    Kindly help me out with this ASAP.

    Thanks again,
    yen

    • CatDaaaady says:

      I checked it out. On atleast Android 1.5 mediaplayer won’t play a file that still has an open FileOutputStream connected to it.
      If you close the FileOutputStream first, then is will prepare and play.

      At least that is my experience. :-) But good tutorial as a guideline how the whole thing works.

  104. Biosopher says:

    This is great, CatDaaaady. Thanks for sharing!

  105. mstudda1 says:

    I am getting this error… http://screencast.com/t/YTI3ZDA4YTIt any help

  106. Zeba says:

    hi,
    Wen i try to run dis tutorial i get the following error….
    Can u please tell me how do I correct it. Thanks.

    E/Player ( 5300): /data/data/com.example.streaming/cache/playingMedia1.dat
    E/PlayerDriver( 36): Command PLAYER_SET_DATA_SOURCE completed with an error or
    info PVMFErrNotSupported
    E/MediaPlayer( 5300): error (1, -4)
    E/com.example.media.StreamingMediaPlayer( 5300): Error initializing the MediaPla
    er.
    E/com.example.media.StreamingMediaPlayer( 5300): java.io.IOException: Prepare fa
    iled.: status=0×1
    E/com.example.media.StreamingMediaPlayer( 5300): at android.media.MediaPl
    ayer.prepare(Native Method)
    E/com.example.media.StreamingMediaPlayer( 5300): at com.example.media.Str
    eamingMediaPlayer.startMediaPlayer(StreamingMediaPlayer.java:189)
    E/com.example.media.StreamingMediaPlayer( 5300): at com.example.media.Str
    eamingMediaPlayer.access$2(StreamingMediaPlayer.java:177)
    E/com.example.media.StreamingMediaPlayer( 5300): at com.example.media.Str
    eamingMediaPlayer$2.run(StreamingMediaPlayer.java:153)
    E/com.example.media.StreamingMediaPlayer( 5300): at android.os.Handler.ha
    ndleCallback(Handler.java:587)
    E/com.example.media.StreamingMediaPlayer( 5300): at android.os.Handler.di
    spatchMessage(Handler.java:92)
    E/com.example.media.StreamingMediaPlayer( 5300): at android.os.Looper.loo
    p(Looper.java:123)
    E/com.example.media.StreamingMediaPlayer( 5300): at android.app.ActivityT
    hread.main(ActivityThread.java:3948)
    E/com.example.media.StreamingMediaPlayer( 5300): at java.lang.reflect.Met
    hod.invokeNative(Native Method)
    E/com.example.media.StreamingMediaPlayer( 5300): at java.lang.reflect.Met
    hod.invoke(Method.java:521)
    E/com.example.media.StreamingMediaPlayer( 5300): at com.android.internal.
    os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
    E/com.example.media.StreamingMediaPlayer( 5300): at com.android.internal.
    os.ZygoteInit.main(ZygoteInit.java:540)
    E/com.example.media.StreamingMediaPlayer( 5300): at dalvik.system.NativeS
    tart.main(Native Method)
    D/Sensors ( 58): sensors=00000000, real=00000000
    D/KeyguardViewMediator( 58): screen is locked
    W/ActivityManager( 58): Unable to start service Intent { action=android.accoun
    ts.IAccountsService comp={com.google.android.googleapps/com.google.android.googl
    eapps.GoogleLoginService} }: not found

  107. monkey says:

    hi,

    when i run the tutorial, there’s not voice,
    and the LogCat appear continuously the message:

    “12-26 13:02:25.844: ERROR/MediaPlayer(742): Attempt to call getDuration without a valid mediaplayer”

    and

    “12-26 13:02:25.905: ERROR/MediaPlayer(742): Error (-38,0)”,
    i don’t know how to solve the problem, do yo know the reason?

    thanks

  108. Biosopher says:

    Hi,

    I finally got around to updating my Android MediaPlayer streaming media tutorial Cupcake (v1.5). I last worked on this code nearly 18 months (for v1.0) so I had to update everything.

    I’ll be posting an updated tutorial in a few days. In the meantime if you need the code, please post here and I’ll send it to you.

    Cheers,
    Anthony

  109. [...] may want to look at my old Android v1.0 streaming tutorial for additional details. I don’t want to rewrite that post completely so I’ll mostly [...]

  110. Senthil.M says:

    Hi Anthony,

    I have an issue regarding video play in android 2.0.1 emulator. When i try to play a video in android 2.0.1 emulator, i am getting a white screen in the view. But audio is working fine, also getting the following error message in the logcat,

    ERROR/SurfaceFlinger(64): layer 0x3f8528, texture=2, using format 32, which is not supported by the GL

    The error mentioned above keeps on repeating in
    the logcat till the end of the video.

    The same video is played without any errors in android 2.0 and previous version emulators. I am not sure about the android 2.0.1 devices. I am getting the above problem even in Apidemo video sample program. Is there any way to resolve this issue or is it an android 2.0.1 bug ? Any help appreciated.

    thanks in advance,
    Senthil.M

    • Biosopher says:

      Hi Senthil,

      Most likely this is a problem with your video file. Can you play this video file in a pre-2.0.1 version?

      I found .3gpp to work well and most other formats to have problems. What format are you using?

  111. Biosopher says:

    What error messages are you seeing?

  112. Tmac says:

    Regarding the video display issues – I have had similar problems. This is what I did and it fixed the issues.

    1. Create an MP4 or 3GP file. Does not matter really. Up to you. There are plenty of utilities for doing this. One of the coolest is http://mediaconverter.org/ Place your newly created file on your hard drive.

    2. Download MP4Box for Windows. Just do a search and download the command line MP4Box utility. This utility, among many other things it does, will add the appropriate headers to allow for progressive download. Do not run the executable from Windows. Place all of the contents in a folder and open a DOS session.

    3. Place your video file in the MP4Box folder. From your DOS session type MP4Box yourvideofilename -hint

    4. Upload your video to the server of choice.

    • Tmac says:

      Also, you will get format errors from MediaPlayer even if it cannot find the URL. I spent hours trying to figure this out when I discovered that the XML I was reading to get my URL path included quotes. :-)

  113. Biosopher says:

    Hi Senthil,

    Are you using the updated code that I released in my revised Streaming Media Tutorial?

    http://blog.pocketjourney.com/2009/12/27/android-streaming-mediaplayer-tutorial-updated-to-v1-5-cupcake/

    Also, did Tmac’s recommendations help solve your problem?

  114. Luis Botero says:

    I found another way to do a similar thing but easier using AsyncPlayer (http://developer.android.com/reference/android/media/AsyncPlayer.html)

    Here’s a short example:

    protected void PlaySound(LocationEntry locEntry) {
    Uri url = Uri.parse(“http://www.pocketjourney.com/downloads/pj/tutorials/audio.mp3″);
    AsyncPlayer player = new AsyncPlayer(“test”);
    player.stop();
    player.play(this.context, url, false, AudioManager.STREAM_SYSTEM);
    }

  115. Riz says:

    Hi Anthony,

    great tutorials . but I am wondering how can I save that file to sqlite database or file system please suggest me ,if I go through the source code I can see commented line
    //FileUtils.copyFile(downloadingMediaFile,bufferedFile);
    if I un-comment is it going to work ……downloadingMediaFile contain every thing ?

    • Biosopher says:

      Hi Riz,

      FUtils refers to code that does not exist so simply delete that commented line.

      The downloaded file is currently being copied to the file system. You can choose to capture the data and save it as a blob to a sqllite db, but the ‘lite’ db or really any db isn’t built for storing files. You should save to the file system and simply store the file path in the db.

      • kavitha says:

        Thanks CatDaaaady,,

        But still there is gap in between switching over of files

        What will be the workaround for that????

        Please tell me solution.

        Thanks
        Kavitha

  116. Biosopher says:

    Hi Kavitha,

    I just tested the streaming tutorial and don’t hear any gaps in the downloaded audio.

    Anthony

    • CatDaaaady says:

      I actually hear it in my app. In my app I am saving pieces of a live, continuous, stream and playing them one by one.
      It is VERY subtle. But I know the gap is there. None of my users have complained about it yet though. So I assume maybe it is only for people with sensitive ears.

      My plan to getting around it is to implement some type of live stream-to-rtp converter. So the program will download a portion of audio, put it into a RTP packet, then send that off to the audio player.

      I “think” this is how other apps are doing it. I haven’t had time to do this just yet. I noticed some links on this page that mention RTP. Maybe they point the way even though it is for video? I think sometime next month, after I add a different feature to my app, I will tackle this rtp thing. I will report back.

      • kavitha says:

        Hi CatDaaaady and Biosopher,

        Thanks for the replies.
        Using catDaaady’s player idea,I am able to play continously an Internet Radio.

        But when i change the Internet Radio link url,file is getting downloaded,but i am not able to play once again,,MediaPlayers hang up without even showing error.

        I am calling player(File f) from another thread and pause it when user clicks on another url,clear mediaplayers vector in clear() ,,and again start thread when file gets downloaded.

        Please tell me the solution.

        Here is what I am doing when i change url

        public void player(File ff){
        final File f = ff;
        final String TAG = “**************************************setupplayer*****:”;
        Log.i(TAG, “File ” + f.getAbsolutePath());
        // Runnable r = new Runnable(){
        // public void run(){
        try{
        MediaPlayer mp=new MediaPlayer();
        try{
        FileInputStream ins = new FileInputStream( f );
        mp.setDataSource(ins.getFD());
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setOnCompletionListener(playerlistener);
        if ( ! started ){
        mp.prepare();
        } else {
        //This will save us a few more seconds
        mp.prepareAsync();
        }
        insertMedia(mp);
        if ( ! started ){
        startMediaPlayer();
        }
        }catch(Exception e){
        Log.e(TAG, “:ERROR********:”+e.toString());
        e.printStackTrace();
        }

        }catch(Exception e){
        System.out.println(“********************ERROR IN PLAYER “+e);
        e.printStackTrace();
        }
        // }
        // };
        // new Thread(r).start();
        }

        MediaPlayer.OnCompletionListener playerlistener = new MediaPlayer.OnCompletionListener () {
        public void onCompletion(MediaPlayer mp){
        onMediaPlayerCompletePlay(mp);
        }
        };

        private void onMediaPlayerCompletePlay(MediaPlayer mp){
        String TAG = “MediaPlayer.OnCompletionListener”;
        Log.i(TAG, “Current size of mediaplayer list: ” + mediaplayers.size() );

        MediaPlayer mp2 = getMedia();
        if(mp2 != null)
        mp2.start();
        mp.release();
        removefile();
        }

        public void insertMedia(MediaPlayer file){
        ///add file at last of vector
        try{
        mediaplayers.add(file);
        available = true;
        }catch(Exception e){
        System.out.println(“EXCEPTION IN INSERTMEDIA”+e);
        e.printStackTrace();

        }

        }

        public MediaPlayer getMedia(){
        try{
        if(mediaplayers.size()<1){
        available=false;
        }

        if(!available){
        return null;
        }
        mediaplayers.remove(0);;

        if(mediaplayers.size()<1){
        return null;
        }
        }catch(Exception e){
        System.out.println("EXCEPTION IN GETMEDIA"+e);
        e.printStackTrace();
        }
        return mediaplayers.firstElement();
        }

        private void removefile (){

        String TAG = "removefile ***:";
        try{
        File temp = new File(context.getCacheDir(),DOWNFILE + playedcounter);
        Log.i(TAG, temp.getAbsolutePath());
        temp.delete();
        synchronized(this){
        playedcounter++;
        }
        }catch(Exception e){
        System.out.println("EXCEPTION IN REMOVEFILE"+e);
        e.printStackTrace();
        }
        }

        //Start first audio clip
        private void startMediaPlayer() {
        String TAG = "startMediaPlayer***:";
        try{
        //Grab out first media player
        synchronized(this){
        started = true;
        MediaPlayer mp = mediaplayers.get(0);
        mp.start();
        }
        }catch(Exception e){
        System.out.println("EXCEPTION IN STARTMEDIAPLAYER"+e);
        e.printStackTrace();
        }

        }

        public void clear(){
        String TAG = "CLEAR URL STREAMPLAYER***:";

        try{
        synchronized(this){
        playedcounter = 1;
        started = false;
        available=false;
        for(int i=0;i<mediaplayers.size();i++){
        MediaPlayer mp=mediaplayers.get(i);
        if(mp != null){
        if( mp.isPlaying())
        mp.pause();
        mp.reset();
        mp.release();
        }
        }

        mediaplayers.removeAllElements();

        }

        }catch(Exception e){
        Log.i(TAG, "ERROR CLEARING MEADIA PLAYERS : " + mediaplayers.size() );
        e.printStackTrace();
        }

  117. CatDaaaady says:

    I am not so sure on that one.
    But maybe in your clear() try

    mp.stop();
    mp.release();

    Instead of
    mp.pause();
    mp.reset();
    mp.release();

    It could be the mediaplayer resources are not getting released properly?

  118. kolos says:

    Hi guys,
    i am new to Android.
    i am trying to stream a video but i always have this error message sorry cannot play video!
    does anybody have a solution??

  119. kavitha says:

    Hi,,

    How to implement media player as service.

    Please suggest.

    Thanks
    Kavitha

  120. CatDaaaady says:

    I converted my streaming player into a service first in revision 19
    http://code.google.com/p/mynpr/source/browse/trunk/mynpr/src/com/webeclubbin/mynpr/StreamingMediaPlayer.java?spec=svn19&r=19

    It took a lot of trial and error, but I bet you can find some tutorials on the net.

  121. meen_onboard says:

    Thanks, this is a great tutorial for me to understand how to streaming music to my Hero.

    • Scission says:

      HI Biosopher

      Big thanks for this very tutorial
      it help me a lof ^^

      Can u provide me plz a example of source code which deals with only local file and not in internet ?

      because the buffer process is a little hard for me ^^
      thx a lot

      ps : sorry for my english and i PM u in anddev ^^

  122. Ron says:

    Hi Biosopher, thanks for the great tutorial.

    I’m an iPhone developer taking my first steps at developing for Android. I have an app on the iPhone that implements the exact functionality you’re describing here so this is a great start for porting it to the Android platform.

    Unfortunately it seems the download link for source code is broken, any chance to get it fixed, of if anyone else has the source code, I’ll be happy to get it.

    Thanks,
    Ron.

  123. [...] some reason the PocketJourney streaming tutorial for Android 1.0 keeps ranking in all my searches, which is generally too bad because that’s way out of date. [...]

  124. Hari says:

    Hi Anthony,

    I tried executing your code in Android emulator. Download is happening properly but I dont hear any audio. I checked playback of an mp3 file in sdcard using the music player in emulator, it works fine. What could be the problem?

  125. Biosopher says:

    Hi Hari,

    Do you see any error messages in the Log?

    Anthony

    • Hari says:

      Hi Anthony,

      Where can I see the log messages in the emulator? Kindly guide me, I will check and get back to you.

    • Hari says:

      Hi Anthony,
      When the download is happening, following error is getting displayed continuously:

      E/MediaPlayer( 247): Attempt to call getDuration without a valid mediaplayer
      E/MediaPlayer( 247): error (-38, 0)
      E/MediaPlayer( 247): Error (-38,0)
      E/MediaPlayer( 247): Attempt to call getDuration without a valid mediaplayer
      E/MediaPlayer( 247): error (-38, 0)
      E/MediaPlayer( 247): Error (-38,0)

      Please let me know why this error happens and how to fix it.

    • Hari says:

      Hi Anthony,

      And the call stack at the end of download is as follows:

      E/PlayerDriver( 31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported
      E/MediaPlayer( 247): error (1, -4)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): Error updating to newly loaded content.
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): java.io.IOException: Prepare failed.: status=0×1
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at android.media.MediaPlayer.prepare(Native Method)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at com.pocketjourney.media.StreamingMediaPlayer.transferBufferToMediaPlayer(StreamingMediaPlayer.java:196)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at com.pocketjourney.media.StreamingMediaPlayer.access$3(StreamingMediaPlayer.java:183)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at com.pocketjourney.media.StreamingMediaPlayer$5.run(StreamingMediaPlayer.java:240)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at android.os.Handler.handleCallback(Handler.java:587)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at android.os.Handler.dispatchMessage(Handler.java:92)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at android.os.Looper.loop(Looper.java:123)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at android.app.ActivityThread.main(ActivityThread.java:4363)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at java.lang.reflect.Method.invokeNative(Native Method)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at java.lang.reflect.Method.invoke(Method.java:521)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
      E/com.pocketjourney.media.StreamingMediaPlayer( 247): at dalvik.system.NativeStart.main(Native Method)
      E/MediaPlayer( 247): Error (-38,0)
      W/PlayerDriver( 31): PVMFInfoErrorHandlingComplete
      E/MediaPlayer( 247): Error (-38,0)
      I/MediaPlayer( 247): Info (1,26)

  126. Biosopher says:

    Hi Hari,

    It looks like you altered the tutorial code slightly. Read the tutorial section for information about “PVMFErrNotSupported”.

    Anthony

  127. Ronak says:

    I was just wondering how can we get details of currently playing song like we get on our computers..

    I want to display the name of currently playing track in a TextBox. Something like below:

    Now Playing:
    Boys like girls – Two is better than one

  128. Rob says:

    This tutorial worked really well on my Motorola Droid. Has anyone been able to get a play list to work like a m3u or pls in the URL? This steams mp3 files really well from my server but I can’t make it play my playlist. I would find this really useful to change the playlist and never have to change the code.

  129. Jonathan says:

    been reading the OP’s code and it looks good but im a bit confused at one thing.

    u store a buffer of the music and replace the old buffered file with the newly downloaded one?

    doesnt this provide a gap between the song your streaming as you have to set the mediaPlayer with the newly buffered music file?

    You say that it is impossible to add content to the file that the mediaPlayer is playing at the moment but what is wrong with simply doing this:

    mediaPlayer.create(context, Uri.parse(“http://media/music/micheal_Jackson.mp3″) )
    mediaPlayer.start();

    Why in the API does it say that the MediaPLayer itself can play content from a url providing the content your plauying supports continues download?

  130. Rishu says:

    Hi
    Please any one tell me . how to play continuous radio. I have try with above tutorial it ‘s playing but after some time due to buffering it not working

  131. HungBh says:

    Hi u , I try to play streaming video with APIDemos, but I can play it with only file famous.3gp of you, i tried a lot of file .3gp but it show some error :
    command PLAYER_INIT completed with an error or info PVMFErrContentInvalidForProgressivePlayback.
    Attemp to call getDuration without a valid mediaplayer.
    can u help me, plzzz
    can u send me some url or video, which APIDemos can streming,
    my email : bhh_10_10_88@yahoo.com
    tks alot!!!

  132. praveen says:

    Hi Biosopher,
    I worked with your Streaming media player. It worked very well for me. Im using this for playing audio stream from radio station url where streaming may be continuous. I increased buffer size to 10Mb in moveFile(oldFileLoc,newFileLoc) method to play continuously. Here sd caching is happening which could result in crash if user has insufficient memory.

    SO is there any another method or player service which works without SD caching.

    Pls let me know the better way to come out of this issue..

    Thanks.

    • Biosopher says:

      Great to hear, Praveen. Many many people have been asking about streaming live audio on Android. 10MB seems like a reasonable file size depending on the bytes/second of audio time being streamed.

      What radio station are you streaming and what format is their stream encrypted into?

  133. Abhijeet says:

    Hi Biospher

    I am a bit new to Android . I was trying to run the MediaPlayerDemo_Video example given in API demos of sample codes . But there was a glitch . My emulator showed the message :-
    “The application MediaPlayerDemo_Video (process com.android.MediaPlayerDemo_Video) has stopped unexpectedly . Please try again. ”

    I am not getting where the problem is . I think there might be some problem with my manifest file , so I am sending you the manifest file that I used .

    I have read the whole discussion . You have been very cooperative throughout . Please help me out !!!

    Abhijeet

  134. Abhijeet says:

    The AndroidManifest file is :-

    Abhijeet

  135. Abhijeet says:

    I am unable to send you the manifest file . I am copying it here in the comment box but it is not publishing the code.
    So you only send me the required files to run it. My id is:-

    abhijeetpatna2008@gmail.com

    Abhijeet

  136. Abhijeet says:

    I am unable to send you the manifest file . I am copying it here in the comment box but it is not publishing the code.
    So you only send me the required files to run it. My id is:-
    abhijeetpatna2008@gmail.com

    Abhijeet

  137. CatDaaaady says:

    God has smiled on us!
    With the android app I have been running, MyNPR, I used Biosopher’s code to get me going playing a live stream of local npr stations.
    My code is here (http://code.google.com/p/mynpr/source/browse/#svn/trunk/mynpr/src/com/webeclubbin/mynpr)
    Yesterday, NPR released the code for the official NPR app for Android.
    Why is this so great? Because they have real live streaming for stations. No saving files locally and playing them in a queue!
    But there is a catch… it is currently not working in the app. BUT looking at their code we can see the direction they are going.

    Basically they are doing what I thought I would have to do to make it all work with out saving files. Take the live stream , repackage the packets into something the mediaplayer can use, then send it to the mediaplayer. I was thinking of converting the live stream to some sort of rtps stream. But NPR is doing something different. I am not sure what though. Check the links below for the code.

    Funny side note: I swear some of their code is “very” close to Biosopher’s code . Even down to the variable names. :-)

    Playback service (where I see some similar code, check lines 328-337)
    http://www.google.com/codesearch/p?hl=en#iRbh2QlHRWY/trunk/Npr/src/org/npr/android/news/PlaybackService.java&q=mediaplayer%20package:http://npr-android-app%5C.googlecode%5C.com&sa=N&cd=1&ct=rc

    Code that translates the live stream:
    http://www.google.com/codesearch/p?hl=en#iRbh2QlHRWY/trunk/Npr/src/org/npr/android/news/StreamProxy.java&q=mediaplayer%20package:http://npr-android-app%5C.googlecode%5C.com&d=7

    Announcement:
    http://www.npr.org/blogs/inside/2010/06/02/127366098/npr-android-and-you
    http://code.google.com/p/npr-android-app/source/browse/#svn/trunk/Npr/src/org/npr/android

    • Biosopher says:

      This is awesome news, CatDaaaady.

      I’ll have to find the time to dig into the NPR app code. If possible, I’ll write an audio streaming tutorial based on the NPR code. This will be an excellent next step for this tutorial…it drastically needs to be updated.

      Cheers,
      Anthony

  138. Abhijeet says:

    Hi Biospher ,

    I have tried the code given in API demos i.e MediaPlayerDemo_Video.java but on executing the code , I just get a blank screen on the emulator and nothing happens (no audio as well) .
    Plz some one help me out !!!!

  139. Abhijeet says:

    Hi biospher

    Besides the API code MediaPlayerDemo_Video.java , I have also tried writing the code the way you told “amit” in one of the posts in this blog (16th february 2009). But the result is same , once again I am getting a blank screen with no video and audio .

    Please Biospher , help me out.

    Abhijeet

  140. Abhijeet says:

    please sum1 reply me ……… i really need sum help !!!

    • Biosopher says:

      Hi Abhijeet,

      Sounds lke your video is not formatted properly. Make sure use a valid format and that your video works in the API Demos code before trying my code above.

      Here is a valid video:
      http://www.pocketjourney.com/downloads/pj/video/famous.3gp

      • Abhijeet says:

        Hi biospher ,
        thnx for the reply . I am using the same file which you have told. Now the problem is that I am getting the audio but , the video stops immediately after the first frame . The audio keeps on going fine but in the surface view only the first frame is being shown.
        I am sending you the code I am using :

        package com.android.VideoPlayer;

        import android.app.Activity;
        import android.media.AudioManager;
        import android.media.MediaPlayer;
        import android.media.MediaPlayer.OnBufferingUpdateListener;
        import android.media.MediaPlayer.OnCompletionListener;
        import android.media.MediaPlayer.OnErrorListener;
        import android.media.MediaPlayer.OnPreparedListener;
        import android.media.MediaPlayer.OnVideoSizeChangedListener;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.SurfaceHolder;
        import android.view.SurfaceView;
        import android.widget.Toast;

        public class VideoPlayer extends Activity implements
        OnBufferingUpdateListener, OnCompletionListener,
        OnPreparedListener, SurfaceHolder.Callback {

        private static final String TAG = “MediaPlayerDemo”;
        private int mVideoWidth;
        private int mVideoHeight;
        private MediaPlayer mMediaPlayer;
        private SurfaceView mPreview;
        private SurfaceHolder holder;
        private String path;
        private String videoStreamURL;
        private Bundle extras;
        private static final String MEDIA = “media”;
        private static final int LOCAL_VIDEO = 4;
        private static final int STREAM_VIDEO = 5;
        private boolean mIsVideoSizeKnown = false;
        private boolean mIsVideoReadyToBePlayed = false;

        public void onCreate(Bundle icicle) {
        Log.d(TAG,”hello”);

        super.onCreate(icicle);
        setContentView(R.layout.mediaplayer);

        Toast.makeText(this,”hi”, Toast.LENGTH_SHORT);

        mPreview = (SurfaceView) findViewById(R.id.surface);
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        videoStreamURL=”http://www.pocketjourney.com/downloads/pj/video/famous.3gp”;

        Log.d(TAG,videoStreamURL);

        }

        public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, “surfaceCreated called”);
        playvideo();
        }

        private void playvideo(){
        Log.d(TAG,”in Playvideo”);

        try {

        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(videoStreamURL);
        mMediaPlayer.setDisplay(holder);

        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnPreparedListener(this);

        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepare();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        } catch (Exception e) {
        Log.e(TAG, “error: ” + e.getMessage(), e);
        }
        }

        public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG,”onPrepared called”);
        mVideoWidth = mMediaPlayer.getVideoWidth();
        mVideoHeight = mMediaPlayer.getVideoHeight();
        if (mVideoWidth != 0 && mVideoHeight != 0) {
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
        }

        }

        public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, “onBufferingUpdate percent:” + percent);

        }

        public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, “onCompletion called”);
        }

        public void surfaceChanged(SurfaceHolder surfaceholder, int i,int j, int k) {
        Log.d(TAG, “surfaceChanged called”);

        }

        public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, “surfaceDestroyed called”);
        }

        protected void onPause() {
        super.onPause();
        releaseMediaPlayer();
        doCleanUp();
        }

        @Override
        protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
        }

        private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
        }
        }

        private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
        }

        private void startVideoPlayback() {
        Log.v(TAG, “startVideoPlayback”);
        holder.setFixedSize(mVideoWidth, mVideoHeight);
        mMediaPlayer.start();
        }

        public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        // TODO Auto-generated method stub

        }

        }

        My .xml file is as follows :

        The manifest file is as follows :-

        Please guide me through this.

        Abhijeet

  141. Abhijeet says:

    My xml file :-

  142. Abhijeet says:

    I am unable to send the xml file and manifest file to you . I am copying it in the comment box but it is not showing up in the post .

    • tiger says:

      thank god for that !!!!
      really, do you know the word spam ? Ever thought you might be applying for the spam-master seeing the incredible amount of stuff you are posting…
      It might be somewhat easier (and smarter) to ask for biosphere’s email adres, IF he is willing to give that for supplying some help, obviously his code is given “as is”, as in : if you can’t get it to work then most probably it has something to do with yourself, like a wrong manifest, wrong project, wrong settings…

      • Abhijeet says:

        hi tiger ,
        thanks for the idea but i thought it would be better to get my doubts cleared over here only so that it may be useful to the people taking up the this project in near future .
        By the way , please help me with this problem of mine . It will be of great use for me

  143. Biosopher says:

    Thanks Tiger.

    Hi Abhijeet,

    Did you change Android’s VideoPlayer demo code at all or did you simply plug-in the URL for my video file?

    What version of Android are you using?

    • Abhijeet says:

      hi Biospher ,

      yes I have changed the code , I have posted it already . If you don’t mind can you please send me your email id , I will send you the complete project of mine.My email id is abhijeetpatna2008@gmail.com

      I am using android 2.1

      • Biosopher says:

        Sadly I don’t have time to review an entire project. What lines of code did you change and why did you change them?

  144. jubin says:

    Hi,

    I have used this code but it is not streaming audio.Will this code work on android emulator.

  145. Daniel says:

    Hey, there.

    Great tutorial. I’ve implemented it, however, and it’s not working properly.

    I’m using Eclipse, and I’m stepping through the code with the debugger, and it appears as though once the download thread is started, none of the code that’s supposed to be handled by the handler is being handled. I’m sure it’s something I’ve done wrong.

    Was there something special that I was supposed to do to ensure that the message handler thread exists? Getting VERY frustrated…

    Thanks,
    Daniel

      • Daniel says:

        Uh, wow. Thanks for you quick reply!

        I changed the handler.post calls to kicking off new threads, and, WHEW, that really made for interesting results… Don’t know what I’m doing wrong.

        Thanks – I’ll try it…

        Daniel

      • Daniel says:

        Thanks, but actually, that threw an exception.

        I’m not sure why the source would have made a difference, though.

        Anyway, let me briefly explain my setup – how it’s different from yours is that I have an array of “media players” that are in a listview (essentially). It’s actually an array of StreamingMediaPlayer objects. Nonetheless, once you get into the actual StreamingMediaPlayer object that is instantiated for the particular row, it should behave no differently than yours (so *I* believe).

        Anyway, that’s the situation – the selected “row” streams the file properly, but handler.post(updater) that is fired off in testMediaBuffer APPEARS to never be run – which leads me to believe that I’m not set up properly – somehow my thread from which these posts are being done (handled) is not right. Why I think this is because of this constructor definition in the API:

        public Handler ()
        Since: API Level 1

        Default constructor associates this handler with the queue for the current thread. If there isn’t one, this handler won’t be able to receive messages.

        Any help is GREATLY appreciated. Stuck in the mud…

        Thanks,
        Daniel

        P.S. I HAVE read both tutorials…

  146. I recommend to look for the answer to your question in google.com

  147. raul says:

    first of all i would like to say that this a great website. my problem is the following:
    i am on the road all the time and i listen to radio stations from my country. When i go to the website and i click on the radio link to start listening, a small windows pops up and show everything except for the windows media controls (pause, play, volume)i have htc evo,with froyo. the small window only shows a square with a little box, obviously is missing the control buttons. is this a codec problem? plugin? any help will be greatly appreciated.

  148. Fabien says:

    Hello,

    When I use a simple MediaPlayer code with icecast mp3 stream, it plays sound from Android 1.5 to 2.2.

    When I use a simple MediaPlayer code with shoutcast, it only plays sound on Android 2.2.

    Do you know why Android 2.1 doesn’t support shoutcast streams like shoutcast streams ?

    Thank you.

  149. Freddy says:

    Hello men,
    First of all thank you for these instructive posts!

    Did one of you tested the MyNPR code using the streamProxy ?
    I tried to use it in order to play Shoutcast streams and was unable to get any results on both 1.5 and 1.6 versions of the API.

    Which solution do you use to play live Shoutcast streams ?
    The best solution I found is CatDaaady’s one. Even if there tends to be some cuts when switching between two captures.

  150. Charlie says:

    Hello,

    First thanks for sharing. I tries this programme on my phone and it works! Now what I want to do it to buffer a live streaming, so I replace the media URL with something like “rtsp://192.168.1.22:554/live”, and this programme seems does not support that. Biosopher, do you have any idea how to modify your code so that it can support live streaming buffering?
    Thanks a lot.

    Charlie

  151. Travis says:

    Hi,

    it just a great tutorial and works fine…
    but what change we have to made if the length in kilobytes of the media file, and the length in seconds of the media file are not known,in order to update the progress bar.

  152. sudheer says:

    Hi,

    I am working on a project where i am sending live video streams from an ip camera to a android phone.

    now i have an idea of sending bidirectional audio both from ip camera and android since they have microphone and speaker. can you please tell me how can we proceed with this?

    thanks & regards,
    karumanchi

  153. Kapil Choubisa says:

    Hi,

    I am new in android and working on os 2.2
    I had tried your code for play streaming .mp3 but not get succeed.
    When I click on Start Streaming. The progressbar shows streaming but I am unable to play the sound. the play button is not working.
    Don’t know why?
    and is there any change with os 2.2 coz this is for 1.5.

    Thank you

  154. SciLor says:

    To bad that the download link is down :( Any chance to send me the source code?

  155. nick says:

    thanku this code works !!!!!!can any one help me in reducing the code here…. i just want to buffer radio station and play… all unwanted error messages want to be removed !!! and other useless stuff

  156. sudheer says:

    Hi,

    Thanks for sharing nice tutorial on audio streaming in android.

    I am doing similar to this, where my task is to play live audio streams coming from ip camera over rtsp/http in .cgi format.

    Is this code is useful for my task. Kindly help me to do so.

    Thanks & Regards,
    Karumanchi

    • Biosopher says:

      Hi Karumanchi. Sadly you’re not the first to ask that question and most likely not the last. Please read through the other posts for everyone’s input on streaming. Short of it still seems to be that there is no easy solution for doing this on Android.

  157. jhulst says:

    Hi,

    Thanks for posting this. I’m looking to use some of it for a local radio station app and I’d like to release my code as GPL. Do you have any restrictions on the code you posted? Any specific license you want it under?

    Thanks,
    Josh

  158. Charlie says:

    Hi Biosopher,

    I try to modify your code so that I can streaming video.
    While in the stratMediaPayer() function, the “File bufferedFile =new File(context.getCacheDir(),getCacheDir(),”playeringMedia”+(counter++)+”.dat”)” only works for the file. After that, the logcat says that “content is truncated”. Do you know how does this happen? Why the code work for audio but not video?
    Thanks a lot.

    Charlie.

  159. Alireza says:

    I am trying to record a voice from Mic using Media Recorder class. in the mentioned class we have just setOutputFile method to set the output file, but I need to get a buffer of some certain recorded voice, I mean i need something like a CallBack method that return a block of recorded byte at that time and i am going to send the mentioned bytes to another device…

    Actually I want to stream and send the recorded voice through socket to another device simultaneously not saving the recorded voice and then read the file and send it, due to it results an unexpected delay…

  160. Carla Castro says:

    Hi,

    I am looking for a tutorial on remote control to control a server. NOT STREAMING audio. I would like to import a .apk into eclipse, but it keeps saying that the “AndroidManifest.xml could not be parsed.” I am a newbie at this, but would really need someone to help me on this.

    Many thanks

  161. ThiloG says:

    Hi…

    Im working on pdf file downloading task.Pdf file is downloading partially, not fully. And also progress bar is not comming. Here i mention about my code. If you find solution means please reply me.

    public class Downloading extends Activity {
    /** Called when the activity is first created. */
    String filePath = “/sdcard/” ;
    String fileName = “one.pdf”;
    BufferedInputStream bos;
    BufferedOutputStream bis;
    //String PATH = “/sdcard/”;
    ProgressBar mprogressbar;
    // pdf = http://www.google.co.in/search?hl=en&client=firefox-a&hs=CdJ&rls=com.ubuntu:en-US:official&q=android+tutorial+pdf&revid=1050297135&sa=X&ei=m4UtTazMNc6WcdnfofEH&ved=0CFcQ1QIoAA

    public String url = “http://www.google.co.in/images?hl=en&client=firefox-a&hs=CdJ&rls=com.ubuntu:en-US:official&q=android+tutorial+pdf&revid=1050297135&um=1&ie=UTF-8&source=og&sa=N&tab=wi”;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.downloading);
    Button increase = (Button) findViewById(R.id.increase);

    increase.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    /*ImageManager im = new ImageManager();
    im.downloadFromUrl(imageName, fileName);*/
    new DownloadFile().execute();

    }
    });
    }//oncreate closing

    public class DownloadFile extends AsyncTask{

    int count;
    //@Override
    protected void onCancelled() {
    // TODO Auto-generated method stub
    super.onCancelled();
    }

    //@Override
    protected void onPostExecute(Boolean downloaded) {
    // TODO Auto-generated method stub

    //super.onPostExecute(result);
    if(downloaded){
    downloaded = false;
    Log.i(“onPostExecute”, “checking download” + downloaded);
    Toast.makeText(Downloading.this, “File is downloaded”, Toast.LENGTH_SHORT).show();
    }
    String filefrom = “/sdcard/one.pdf”;
    File file1 = new File(filefrom );
    if(!file1.exists()){

    }
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file1));
    intent.setFlags(2);
    intent.setClass(Downloading.this,PdfViewerActivity.class);
    startActivity(intent);

    }

    //@Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    //super.onPreExecute();
    }

    //@Override
    protected void onProgressUpdate(String… values) {
    // TODO Auto-generated method stub
    //super.onProgressUpdate(values);
    //mprogressbar.setProgress(Float.parseFloat(values));
    }
    @Override
    protected Boolean doInBackground(File… params) {
    // TODO Auto-generated method stub
    try {
    URL url1 = new URL(url);
    Log.i(“DoInBackground “, “url1….” + url1);
    File file = new File(filePath + fileName);
    Log.i(“DoInBackground “, “filePath….” + filePath + “fileName…..” + fileName + “file…” + file);
    URLConnection conection = url1.openConnection();
    conection.connect();

    int file_length = conection.getContentLength(); // for progress as 1-100 %
    //for download file
    InputStream is = new BufferedInputStream(url1.openStream());
    Log.i(“DoInBackground”, “Inputstream is” + is + ” url1.openstreat()…. ” + url1.openStream());
    OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
    Log.i(“DoInBackground”, “OutputStream is… ” + os + ” FileOpStream()… “);
    byte data[] =new byte[1024];
    int total = 0;

    while((count = is.read(data)) != -1){
    total += count;
    Log.i(“DoInBackground”, “total count…” + total);
    publishProgress((int)total*100/file_length);// progressing
    os.write(data, 0, count);
    }
    os.flush();
    os.close();
    is.close();

    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    boolean downloaded = true;

    }

    return true;
    }

    }

    }

  162. Dharmin says:

    Thank you soo much for the great tutorial. You rock!!

  163. foob says:

    please can u giv teh codez? All your dropouts are belong to us.

  164. deepz says:

    thanks for such a great effort………… really helped a lot

  165. Rimi says:

    Hi all

    I am new in android and working on streaming.The totorial is helpful and easy to understand. But while launching I get some errors as installation error of missing shared libraries.Wiil be greatful if you could help out in this.

    Thanks in advance
    Rimi

  166. Rimi says:

    Hi all

    I am new in android and working on streaming.The tutorial is helpful and easy to understand. But while launching I get some errors as installation error of missing shared libraries.Wiil be greatful if you could help out in this.

    Thanks in advance
    Rimi

  167. sandroid says:

    Hi Guys,

    This tutorial has been really helpful, i have not read all the previous posts since there are many. The only problem with this tutorial is that, 1. Its very complicated logic 2. Lot of gaps in audio 3. CPU intensive.

    I have achived to get rid of all 3 problmes, by using my very own inbuilt http server. Which works like a charm. I can have a tutrial on this, if anyone is intrested. Just let me know.

  168. [...] best solution short of downloading the entire file and then playing from a local resource? I saw this but that seems extremely “hackey”. Could you use a URI with a custom ContentProvider [...]

  169. rockin says:

    it works fine for me ..but problem with the progress bar…it plays the song if the progressbar reaches the end also.

    any solution ??

  170. Rjn says:

    hi everybody…

    i was create music player which is properly stopping and pausing. but
    when i exit the app the music run in background which i need.but when
    i enter the app again it starts to play new song then the problem is
    that could hear the both songs..so i need some help about this
    topic..p

    please help…

    thanks in advance…

    regards.

    Rjn.

    • Biosopher says:

      Hi Rjn,

      At the moment, you are creating a new MediaPlayer each time the Activity resumes. Instead, you need to see if a Media Player is already present in onResume(). If it is present, then restart in onResume(). Also stop the MediaPlayer in onPause() and save the current position of the media.

  171. João Paulo says:

    Hello,

    Its possible to stream audio with MMS Protocol in Android?

    Thanks.

  172. chafo says:

    Hello,
    CatDaaaady,could you please give the URL of the streaming radio that you’ve tested your code, I tested with some urls, but it doesn’t work.

    Thanks.

  173. Paul says:

    This is a great tutorial! Thanks so much, I’ve used this and modified to slightly to work with some custom streaming solutions..

    One thing that I have noticed.. When streaming there are always noticeable pauses when the media players “switches” between the buffered files..

    Do you have any suggestions as to how to rectify this?

    • Is this issue when MediaPlayrer switches files or is the silence actually empty ‘silence’ in the audio files themselves. File switching should be very fast and not noticeable. People (see above) have commented on gaps in audio stored to the buffer files.

  174. hi

    I used the code. Its working fine for only songs with bitrate 128kbps. It only plays little part of song for higher bitrates. And only when song is fully streamed then it starts playing full song.

    Please help

  175. sittu says:

    can u help me in creating a media player with themes…?

  176. savan patel says:

    can u send me code for random media player…
    in this media should stream form the web..
    also mp3…
    and also able to play from own phone…..

  177. dunghoang says:

    Hi Biosopher, great tutorial!
    I used and played. But, when i running a audio from internet, it’s very shock . Because it run parts, help me

  178. Hunain says:

    http://www.pocketjourney.com/downloads/pj/video/famous.3gp

    i have tried to play video and audio both but it starts playing and after 2 or 3 seconds it stuck and stops playing while progress shows streaming complete but the video won’t play after 2 or 3 seconds
    error log

    08-07 11:27:40.661: ERROR/com.pocketjourney.media.StreamingMediaPlayer$3(6583): Error in MediaPlayer: (1) with extra (-1004)

  179. walter says:

    Hi,
    this streaming audio code is very cool, but, something i don’t understand,
    where do i insert my URL in this code…

    I’m a newbie/beginner as android coder ;)

    thanks of your answer

    Williams

  180. Vipin Sahu says:

    Hello
    I am making an apps that is some what similar to your one i tried your code it working fine ,..however Dear I am required to stream video ..not from the streaming server but from the sdcard in the way ie progressive however when i used……
    InputStream in;
    try {
    in = new BufferedInputStream(new FileInputStream(mediafile));
    }
    catch(FileNotFoundException e){

    }
    instead of connecting to url I used it…
    It worked fine for me when the file is mp3 ….

    for mp4 it used surface view and holder and i have set the anchorview for it … but the problem is that it is not progressively streaming the mp4 or a file less than the size of 9M work well above that the apps seems to Not Responding …
    please suggest me …………..

    • Vipin Sahu says:

      Also i have Increased the Size of Initial buffer As video is being played from 120 to 256 and 512 but it also not worked ….

      • Vipin Sahu says:

        hey pls help me out… l founded the problem in case I m using video Streaming the initially loaded buffer does not contain the supported format and footer information …and we are update the content using hte post method of handler …that put the item in queue which update the UI but in case of video It will buffer till last and then dispatch to ui so…. I have to use some thing else………..

  181. chenmin says:

    Hi,
    I ran your codes for testing, it seems error happen in “prepare()”, I think it because non-complete mp3 file can’t be opened.
    My system is android2.3.4, Galaxy S2.

  182. sofian says:

    hy….i want to record from internet radio..can u help me??

  183. [...] Android Tutorial 3: Custom Audio Streaming with MediaPlayer « Pocket Journey [...]

  184. Praveen T says:

    Hi, Thanks for this awesome tutorial. Lot of my doubts got cleared and I could learn lots from here.
    I’m new to android and currently working to stream a video instead of the audio streaming presented here. I modified the code to show a video but then I couldn’t. The extra code that I have added is:
    1) Add a surface view to the xml page.
    2) get a SurfaceHolder for the same in the constructor block of “StreamingMediaPlayer”
    3) I modified the method createMediaPlayer(File file) as shown below:

    private MediaPlayer createMediaPlayer(File mediaFile)
    throws IOException {
    MediaPlayer mPlayer = new MediaPlayer();
    mPlayer.setOnErrorListener(
    new MediaPlayer.OnErrorListener() {
    public boolean onError(MediaPlayer mp, int what, int extra) {
    Log.e(getClass().getName(), “Error in MediaPlayer: (” + what +”) with extra (” +extra +”)” );
    return false;
    }
    });

    // It appears that for security/permission reasons, it is better to pass a FileDescriptor rather than a direct path to the File.
    // Also I have seen errors such as “PVMFErrNotSupported” and “Prepare failed.: status=0×1″ if a file path String is passed to
    // setDataSource(). So unless otherwise noted, we use a FileDescriptor here.
    FileInputStream fis = new FileInputStream(mediaFile);
    mPlayer.setDataSource(fis.getFD());
    mPlayer.setDisplay(surfaceHolder);
    mPlayer.prepare();
    surfaceHolder.setFixedSize(400, 300);
    return mPlayer;
    }

    4) In the method “transferBufferToMediaPlayer()” I did not call the method createMediaPlayer(File file) instead I wrote a new method appendNewDownloadData(File file) as shown below:

    private void appendNewDownloadData(File bufferedFile)
    throws IOException {
    FileInputStream fis = new FileInputStream(bufferedFile);
    mediaPlayer.reset();
    mediaPlayer.setDataSource(fis.getFD());
    mediaPlayer.prepare();
    }

    Summary of what I have added to the code:
    1) Added a SurfaceView to the XML
    2) Got a SurfaceHolder from the SurfaceView
    3) Used the api’s :
    MediaPlayer.setDisplay(SurfaceHolder)
    SurfaceHolder.setFixedSize(int, int)

    Could any help me achieve this video Display. Thanks in advance.

    @ Biosopher: Do you have any updated tutorial for video Streaming???

    Cheers,
    Praveen.

  185. aru says:

    is it possible to stream voice real time instead of songs???lik a call in pt to pt connection?? pls reply

  186. marek says:

    Thanke you. I use your tutorial to create my program openwebradio on the site http://www.openwebradio.mobi

  187. Ketan Bhangale says:

    Hi,

    Nice tutorial and very well explained.

    I am new to android development and I have tried your code. it working fine on my device. but i want to stream video. I have made some changes to your code(added surface view) but not able to get it correct.

    current output: first file gets fully loaded and then start playing instead of parallel downloading and playing.

    Please please help me or if anyone has above code converted for video. please post it or email me(ketub4@gmail.com)

    Thanks in advace.

    Ketan B

    • Biosopher says:

      What file format are you using, Ketan? I have had great success with .3gp. Try streaming this file:
      http://www.pocketjourney.com/downloads/pj/video/famous.3gp

      • Ketan Bhangale says:

        Hi Biosopher,

        Can you please send me your above code modified for video on my e-mail id(ketub4@gmail.com). I am using Your url mentioned above but media player starts and after 1-2 sec is stops playing but downloading completes in the background.

        The above mentioned url is working properly in MediaPlayerDemo_video in api demos but it stucks when i am trying to play mp4 file with large size say 13 to 15 MB. I have added header using MP4Box to mp4 file so that it can play as per Tmac’s comment above.

        Please help me… its very critical time for me….

        Thanks in advance…..

        Ketan B

      • Ketan Bhangale says:

        Hi Biosopher,

        I have sent my code in the comment yesterday. but it is not get published I guess.
        Thanks for your immediate reply.

        Ketan B

  188. Biosopher says:

    Hi Ketan,

    My tutorial is meant only for streaming audio files…and was only tested with .mp3 files. I wrote that code awhile ago and haven’t updated it since Android v2.0.

    Videos play fine using Android’s built-in streaming video player as you saw using the MediaPlayerDemo. Just make sure you use a media format supported by Android. Getting the media files formatted correctly can be rather tricky which is why I recommend starting with the .3gp file I mentioned earlier.

    If you’re having problems with .mp4, reformat to .3gp using Quicktime Pro. I had great success with it…though it does cost about $40. I think you can try the demo.

  189. kai says:

    Thanks to this tutorial. :) I have noticed that you are passing hard coded mediaLengthInKb and mediaLengthInSeconds. Is there any way of getting these values dynamically? in order to update the seekbar properly. Thanks!

    • Biosopher says:

      You can pass those values in the HTTP header if you have control over your web server at that level. Otherwise, you can parse the MP3 header after those first few bytes have downloaded…at least for .mp3 files where those details are in the header. The file size should come from the HTTP header regardless of any actions on your part, however you’ll need to know the compression rate to determine the length is seconds. Well…you can calculate that immediately if you know all your files are compressed at the same bit rate.

      • kai says:

        Thanks for the response. I was able to manage getting the mediaLengthInKb from the header. However, I am having a problem converting it to mediaLengthInSeconds. Do you have any formula for that, assuming that I know the compression bit rate? thanks!

      • kai says:

        By the way, do you know how can i get the bit rate? from the header? or how can i possibly estimate it? thanks!

      • kai says:

        Hey, I was able to manage this now. Thank you! :)

  190. hndr91 says:

    Reblogged this on randomarticlez and commented:
    nice ! i’ll try it !

  191. bams says:

    Hi guys,
    Is there any tutorial to build app that can stream encripted audio file?

    Just as radio online but has username and password to stream it.

    Thanks a lot :-)

  192. [...] may have seen my prior post on this topic: Streaming Media with Android.  The title is slightly innacurate as it’s less about generic ‘media’ streaming [...]

  193. [...] may have seen my prior post on this topic: Streaming Media with Android.  The title is slightly innacurate as it’s less about generic ‘media’ streaming [...]

  194. dungbt says:

    some links have broblem with this code,it throws error “pause call in state 128″ and “error (-38,0)”
    Someone know about that?

  195. dungbt says:

    the problem appear when i stream wav file,but with mp3,it works perfectly
    so,wav is the problem?

    • Biosopher says:

      Stay with .mp3 if you can. The file sizes are smaller and thus download faster. Android appears to have better .mp3 support as well.

  196. shadab says:

    Hi Biosopher,

    Its very good tutorial. can you just provide a complete application for live streaming as i am new to android.

  197. shadab says:

    while streaming audio is not playing

  198. Zeeshan Abid says:

    Hi Biosopher,

    I have read the tutorial. It is great. I have a problem that i want to record the stream with the playing of media player. I mean if I am streaming and can record the stream with specific duration then how can i record it. ?

    Please help

  199. goto says:

    goto…

    [...]Android Tutorial 3: Custom Progressive Audio Streaming with MediaPlayer « Pocket Journey[...]…

  200. Srikanth says:

    Hi,
    i want to stream an audio song without downloading it.i just used that
    mediaplayer.setDataSource(“http://my server.com/Songs/abcd.mp3″);
    its working fine when its having the wifi connection and GPRS.
    The problem is when using GPRS streaming is very slow.what can i do to speed up the streaming when low bandwidth.I just want to stream that song not to download.
    can anyone help me with an example.
    thanks in advance.

  201. Santanu says:

    Nice posting. Very needful….works fine in my Galaxy ace.

  202. Mohamed N. says:

    What if i want to stream a url like this http://shoutmedia.abc.net.au:10326/.
    What can i do ?

  203. Julius says:

    Hey
    It plays ~3 seconds for me then stops to play sound and continues to load mp3 file. When it is fully loaded then it can play to the end. Hitting pause button couple times plays it for ~3 sec again. Any solution?

  204. Nithya says:

    How can i track Audio streaming from a specified duration of Stream (0-to-Stream Duration)..?

  205. TitaniuM says:

    Hello,

    I am using StreamingMediaPlayer.java to create an audioStreaming object but I am getting error:

    11-20 22:54:01.089: D/MediaPlayer(30855): pause() in
    11-20 22:54:01.089: E/MediaPlayer(30855): pause called in state 0
    11-20 22:54:01.089: D/MediaPlayer(30855): pause() out
    11-20 22:54:01.099: D/MediaPlayer(30855): start() in
    11-20 22:54:01.099: E/MediaPlayer(30855): start called in state 0
    11-20 22:54:01.099: D/MediaPlayer(30855): start() out
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): Unable to initialize the MediaPlayer for fileUrl=http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): java.net.UnknownHostException: http://www.hrupin.com
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at java.net.InetAddress.lookupHostByName(InetAddress.java:509)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:297)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at java.net.InetAddress.getAllByName(InetAddress.java:259)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:69)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:48)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at com.androidhive.musicplayer.StreamingMediaPlayer.downloadAudioIncrement(StreamingMediaPlayer.java:92)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at com.androidhive.musicplayer.StreamingMediaPlayer$1.run(StreamingMediaPlayer.java:75)
    11-20 22:54:01.109: E/com.androidhive.musicplayer.StreamingMediaPlayer$1(30855): at java.lang.Thread.run(Thread.java:1027)

    ——————–

    In my main activity class if I simply do

    MediaPlayer mp = new MediaPlayer();
    mp.reset();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setDataSource(“http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3″);
    mp.prepare();
    mp.start;

    Then everything works fine. I have also tried tamping with the StreamingMediaPlayer and passed mp as a parameter and then doing the following mp = audioStreamer.getMediaPlayer(); but it still doesnt work. I have spent 3 days already trying to debug it but I cannot, please help.

    Thank you

  206. TitaniuM says:

    Also, I have pinged the host and its up and running. I have tried 3 different URLs and they work if I dont use StreamingMediaPlayer. I would love it if I can fix this issue.

  207. ashok says:

    How to play rtmp streaming video in android emulator, geting connection in anctivity, pls give sample code…

  208. aditya says:

    i am using your code ,it only streams the audio but don’t play that audio.Please help me in this

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>