NOTE: 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.

After spending the last year game programming on the iPhone, I’ve finally returned to Android.  My six prior tutorials were outdated (Android v1.0) so I took the time to update them to v1.5 (Cupcake).  The most popular of those tutorials was the Streaming MediaPlayer tutorial so that’s the primary focus of this post.

Tutorial #3 results screenshots

At the time of initially writing the streaming tutorial, Android’s media streaming function didn’t work well so I wrote my own.  As of v1.5 however, Android’s MediaPlayer streams very well.  That said, it’s still useful to know how to retrieve a media file from a server and store it on the device.  This would be useful to immediate replay of the file at a later date or for caching files for later playback ‘off the grid’.

Download the source files to get started immediately and then view the rest of the tutorial after the jump.

You 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 focus here on the changes required for Android v1.5. That said, there is very little difference between my old tutorial and this new one.

The most important change is that MediaPlayer.setDataSource() now takes a FileDescriptor instead of a String path to the media File. It seems the reason to use FileDescriptors is for security/permission reasons. In either case though, passing a String path to our media File resulted in errors such as “PVMFErrNotSupported” and “Prepare failed.: status=0×1″. So until I learn otherwise, I recommend using FileDescriptor for the MediaPlayer.


FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());

The only other change is I can no longer find any File move functionality it Android so I wrote my own. It does exactly what it says, it moves data in one File to a new File location. This is used while streaming the media file so we can double buffer it. The double buffering allows us to simulaneously download to one File while playing from another File. We sync the downloaded data between the Files as more data is downloaded:

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

Download the source files for all the tutorials. The streaming media tutorial available by clicking button #3. Don’t forget to look at my old Android v1.0 streaming tutorial for additional details.

Share →

113 Responses to Android Streaming MediaPlayer Tutorial – Updated to v1.5 (Cupcake)

  1. [...] Android Streaming MediaPlayer Tutorial – Updated to v1.5 (Cupcake) « Pocket Journey Trackback on December 27, 2009 at 9:30 [...]

  2. Hapoo says:

    I implemented your new revision and it works fine for the first file I play albeit with a stutter at data swaps. I can’t seem to get it to load any subsequent files though. I’ve gone so far as trying to load a new instance of it, but it merely crashes the program. Any ideas or hints you can give me?
    Thanks

    • Biosopher says:

      The tutorial app was only designed to load & play a single file. You would need to add MediaPlayer shutdown and cleanup at the end of the file playing for it to download and play another file (exercise for the reader).

      With a restart though, I was able to load and reload files without problems. What error message are you getting?

    • Tim says:

      I try to use this to play a shoutcast but there are always gaps between the files.
      Any ideas how to improve this?
      I tried different buffer sizes, but there is no solution.
      I’m using the code from the 1.5 tutorial.

      I’m getting the “PVMFErrNotSupported”-failure, too

  3. Hapoo says:

    Thanks for the rapid response!!

    I’m not getting any errors… none that I can detect anyway. I tried reseting the mediaplayer before calling startstreaming(…) again, but that didn’t work either, it didn’t do anything. If I had an idea as to where it was locking up it would make it much easier to fix.

    At this point with the new sdks, is this still a beneficial route to go for streaming? Doesn’t the standard mediaplayer buffer the data? The only real reason I’m going through all this is because I want the entire mp3 file loaded on to the device so if someone rewinds/fastforwards the file doesn’t reload from the server and I’m not sure if mediaplayer does this automatically.

    • Biosopher says:

      I’m unsure how Android handles the buffering upon fast forward/rewind. My tutorial was written before Android’s streaming was working well. I’m fairly happy with the built-in streaming of v1.5 so I don’t use my own code anymore.

      Anthony

  4. Nenad says:

    I have modify code little bit so it can work on my HTC Tattoo (1.6). Then I tried it and it’s not working. when I press button play it start downloading file without playing anything.

    I’m begginer in Android programming.

    Help please … thanks.

  5. DinDin says:

    I am trying to do some live video delivery to the android platform. I have done this for the iPhone and given Apple’s HTTP adaptive streaming, this is made very easy. But not so on Android. What path would you recommend?

    I am writing along the lines of what you have done (thanks for the examples) but I don’t want to have glitches when switching between files. Would be made simpler if there was a way for Android to implement something like M3U8 or another video playlist playback mechanism.

    • Biosopher says:

      Hi Din Din,

      I didn’t include this in the tutorial as I wasn’t sure it would work at the time. However as the MediaPlayer is currently written, you don’t need to double buffer the streamed media as in the current tutorial. You can actually just write directly the file as it’s playing.

      You would need to add logic to pause playback if the playback exceeds the amount of downloaded file though.

      Anthony

      • Hapoo says:

        I discovered this today. The only catch (in my case anyway) is that you have to allocate space for the entire file first.

  6. Biosopher says:

    Hi Hapoo,

    You can always allocate a given amount of file space and stream to it until it’s full. At that point, allocate a new File for streaming then create a new MediaPlayer to point to the new File.

    • Nissar says:

      Could anybody please explain how to pre-allocate the memory in SDCard so that no other application can access this space. If we are maintaining a queue for downloading, how to pre-allocate(or lock) a partcular amount memory space in external storage, so that whatever in queue can be downloaded safely. Is there any other work arround than filling the space with dummy data?

      • Nissar says:

        . Could anybody please explain how to pre-allocate the memory in SDCard so that no other application can access this space. If we are maintaining a queue for downloading, how to pre-allocate(or lock) a partcular amount memory space in external storage, so that whatever in queue can be downloaded safely. Is there any other work arround than filling the space with dummy data??

  7. Biosopher says:

    Hi Nenad,

    It would be easiest if you could quickly tell me how you altered the code to work on your Tattoo. Also explain why you had to alter it to work on your Tattoo.

    Thanks,
    Anthony

    • Nenad says:

      It’s working :)
      I was thinking that I need to change version to 1.6.
      Thanks. :)

      Is it posible to stop mp immediately when I press back button?
      Now it’s playing whole (downloaded part) of mp3 file.

      Your Tutorials are fantastic!
      Thank you very much for helping us to learn programming in Android!

      • Biosopher says:

        You can setup the MediaPlayer to stop and restart. Just listen to the buttons, test for the MedaPlayers current state (playing, paused), and take the appropriate action.

  8. Tiger says:

    Just out of curiousity, will this work on a real stream ? Not by streaming a (size definite) MP3 file from a server… And if so what kind of modifications does the code need ?

    • Biosopher says:

      First that would depend on the format of the stream and whether Android’s MediaPlayer supports that media format. Android’s media support is fairly minimal.

      If it was a supported stream though, I would recommend simply using Android’s MediaPlayer as there would seem to be little reason to download and cache the stream yourself.

      However if the stream was supported, then I don’t know why this approach would not work.

      • Tiger says:

        well basically because in your code I see that you are supplying a size to the startStreaming() method of the StreamingMediaPlayer class

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

        so what should be supplied for a real stream ?

        Also the formats would be (ideally) AAC(+)/MP3/AMR-WB throught rtsp or http…

        My tests confirm a working MP3 through rtsp with the inbuilt mediaplayer but for example I am not able to play a .3gp rtsp stream using AAC+…
        Any idea’s or experiences on how to get that to work ?

  9. Biosopher says:

    Hi Tiger,

    I just looked at the supported media types for Android:

    http://developer.android.com/intl/zh-CN/guide/appendix/media-formats.html

    That list doesn’t say anything about support for streaming formats. File-based media typically have a header with information about the file. Streams provide that information in other ways. That would seem to preclude saving the stream to a file for replay as a file-based format.

    In short unless Android supports streamed audio, I doubt this tutorial would be much help.

  10. Tiger says:

    hhmmm ok, sounds plausible :D
    Not very happy to hear that even with a new and modern platform we still aren’t able to actually stream AAC(+) content… Seems like they looked a lot at J2ME and decided that a 6 year old platform still is a good way to go :(
    I did try your project, and it works, but I did notice that on my device (Android dev Phone 2, which is a HTC Magic running 1.6) the “holes” inbetween the played pieces have a tendency to grow through time… So if the first couple of switches between chunks souns decent after 6-7 switches it will start to have holes of several seconds… Is this normal ?

    • Biosopher says:

      There shouldn’t be any gaps in the downloaded audio files. Are you saying that once you’ve downloaded the audio files, the final file residing on the device has gaps in the audio?

      What audio file are you streaming? Could you confirm this by streaming this file:

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

      • Tiger says:

        Hi,
        first of all sorry for the old reply but here it is :

        [quote]Are you saying that once you’ve downloaded the audio files, the final file residing on the device has gaps in the audio? [/quote]
        Nope the files themselves were ok, but there is a gap which keeps getting bigger inbetween the stopping of a file and the starting up of the next one… So inbetween “chunks” (files in this case)…
        I heard though that ogg would be faster thus completely removing those gaps, only my source is mp3 so is there some way, to your knwoledge, to encode mp3 to ogg in Android itself ?

  11. Tanmay says:

    Hey.. thanks for the excellent tutorials and the time you have put in to help everyone developing android apps.

    I am working on something which is close to the streaming media player but a little different. I want to be listening on a port on my phone for some raw audio data, that will be sent from a location on my network using netcat. I pretty much want to perform a netcat listen function on my android and pipe out the data to the audio hardware. You must have worked or heard about the AudioRecord and AudioTrack classes which give access to raw media.

    I was wondering if you could refine the following algorithm for me and point me to the implementation, as I know a bit of java but not too confident with using Sockets, Pipes and Android stuff.

    The procedure i am planning to use is:

    1) Use a new ServerSocket(port) to listen on particular port.
    2) The other side connects to this port using netcat :
    3) Make a new Pipe which takes the outputstream from the socket, and feeds it into the input of the audio hardware.
    4) Use methods from AudioTrack to play the raw audio in real time

    Any help in this area would be very much appreciated, as I have been struggling to find anything in this area.

    Cheers..
    Tanmay

    • Biosopher says:

      Hi Tanmay,

      That’s quite the challenge you’ve set for yourself. Seems like mostly a networking challenge at this point to get the audio onto the phone. (1) should be easy as I’m sure there’s documentation on the web about it.

      For (2), I don’t know anything about netcat. Why are you using it? I assume there’s a reason you’re connecting from the server to the phone rather than vice versa? I would guess you want to push the data to the phone but don’t want the phone wasting battery power by constantly polling the server for data.
      How is your server going to discover the IP address of your phone though? My worry is that the IP address changes as the phone roams.

      (3) should be documented on the web. For (4), look here:
      http://hashspeaks.wordpress.com/2009/06/18/audiorecord-part-4/

      • Tanmay says:

        Hey, Thanks for the prompt reply.
        Yup, its a challenging one, but quite fun to do ! I will probably elaborate on my project a bit more to give u a slight picture of what we I am doing.
        My first step, which is complete now, was to look at MightyOhms Wifi Radio Project and transform it into a full duplex audio comms system between two routers (with USB sound cards) by installing OpenWRT on it. Its just a linux flavour to unleash your router. I set up one of the routers as an Access point and the other as a client, and by using netcat as I said above and a recorder/player program on the routers I was able to achieve this setup.
        So all that is good. Now, I was looking at replacing the client side router, with another wifi client..ie. the Android phone.
        The comms has to be real time, thats why I am not going for polling. IP address on roaming is not an issue, as being my own lan, I can use static IP addressing.
        So yeah, this will help me establish a 2 way audio path.

        For step (4), i already looked at the code from http://hashspeaks.wordpress.com/2009/06/18/audiorecord-part-4/ and made it into an android project, however, when I heard what I recorded, It seemed like something is overdriving the microphone. And I seem to be having no control on that via the API. Whatever I record closet to the phone turns into clipped garbage, but sounds from far away are clear.

        It would be a huge help if you could test that code on hashirs blog on an android G1 phone running 1.6(which I tested it on) , so that I can confirm its not something I am doing wrong or something to do with my phone.

        Many thanks
        Tanmay

  12. Biosopher says:

    Hi Tanmay,

    I’m using Hashir’s code to record from both a G1 & HTC Ion’s microphone. The only problem I’ve found is that 8 bit audio has a problem. If I use 16 bit, everything works fine.

    • Tanmay says:

      Hey .. Just found the solution to my problem !
      It was just endianness ! I shud hv been careful while playing the file on an intel PC, and specify Big endian format for audio. My problem was that it was recording correctly, but listening in the wrong format introduces noise in the recording (but still records ..which is why i never thought it cud be the parameters) ! I heard the right one in audacity, as it let me choose between endianness.

      All sorted now, thank you for the help.

      Now onto the networking stuff !

      Cheers.
      Tanmay

  13. Draffodx says:

    Hi Biosopher,

    Thanks for the excellent tutorial.

    I currently record sound from the mic and save it to a 3gp file on the sdcard.

    What I want to do is be able to record straight from the mic and play what I’m recording back out with only a 1 second delay.

    Is this possible do you know? Would the code from your StreamingMediaPlayer be usable with changes to do this and a good place to start?

  14. mitu says:

    Hi, I tried to run your streaming program but I got these errors in logCat :

    01-21 20:41:23.995: ERROR/Player(1839): 122880
    01-21 20:41:23.995: ERROR/Player(1839): /data/data/com.pocketjourney.tutorials/cache/playingMedia1.dat
    01-21 20:41:24.165: ERROR/PlayerDriver(51): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported
    01-21 20:41:24.175: ERROR/MediaPlayer(1839): error (1, -4)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): Error initializing the MediaPlaer.
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): java.io.IOException: Prepare failed.: status=0×1
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at android.media.MediaPlayer.prepare(Native Method)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at com.pocketjourney.media.StreamingMediaPlayer.startMediaPlayer(StreamingMediaPlayer.java:185)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at com.pocketjourney.media.StreamingMediaPlayer.access$2(StreamingMediaPlayer.java:173)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at com.pocketjourney.media.StreamingMediaPlayer$2.run(StreamingMediaPlayer.java:153)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at android.os.Handler.handleCallback(Handler.java:587)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at android.os.Handler.dispatchMessage(Handler.java:92)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at android.os.Looper.loop(Looper.java:123)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at android.app.ActivityThread.main(ActivityThread.java:4203)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at java.lang.reflect.Method.invokeNative(Native Method)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at java.lang.reflect.Method.invoke(Method.java:521)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
    01-21 20:41:24.185: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1839): at dalvik.system.NativeStart.main(Native Method)
    01-21 20:41:24.185: WARN/PlayerDriver(51): PVMFInfoErrorHandlingComplete
    01-21 20:41:24.195: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.195: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.195: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.205: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.205: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.205: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.215: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.225: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.225: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.225: ERROR/MediaPlayer(1839): Attempt to call getDuration without a valid mediaplayer
    01-21 20:41:24.225: ERROR/MediaPlayer(1839): error (-38, 0)
    01-21 20:41:24.235: ERROR/MediaPlayer(1839): Error (-38,0)
    01-21 20:41:24.235: ERROR/MediaPlayer(1839): Error (-38,0)

    and continuing….

    So what is it causing for I can’t understand. I’m trying to run it on real device and my SDK is 1.6

    I’m waiting for the reply.

    thanks,
    mitu

    • Biosopher says:

      Hi mitu,

      Seems like you’re using a file format that isn’t supported by Android. Only these formats are supported:

      http://developer.android.com/intl/zh-CN/guide/appendix/media-formats.html

      You can try using this file for testing as .3gp is supported by Android: http://www.pocketjourney.com/downloads/pj/video/famous.3gp

      • Mitu says:

        hi Biosopher, I tried it with mp3 format and I found it is supported media format. In fact I tried to run it with your codebase url without changing it and got previuos errors that I posted to you. Now I tried with wma format uploading to my own site and got the following error in logCat:

        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): Error updating to newly loaded content.
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): java.lang.NullPointerException
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at com.pocketjourney.media.StreamingMediaPlayer.transferBufferToMediaPlayer(StreamingMediaPlayer.java:205)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at com.pocketjourney.media.StreamingMediaPlayer.access$3(StreamingMediaPlayer.java:201)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at com.pocketjourney.media.StreamingMediaPlayer$5.run(StreamingMediaPlayer.java:265)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at android.os.Handler.handleCallback(Handler.java:587)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at android.os.Handler.dispatchMessage(Handler.java:92)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at android.os.Looper.loop(Looper.java:123)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at android.app.ActivityThread.main(ActivityThread.java:4203)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at java.lang.reflect.Method.invokeNative(Native Method)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at java.lang.reflect.Method.invoke(Method.java:521)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
        01-22 14:10:15.965: ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): at dalvik.system.NativeStart.main(Native Method)

        So please show me the way what I should do or if anything I’m doing wrong.

        Thanks,
        mitu

  15. Mitu says:

    Sorry to mention that My device is T-Mobile running Android 1.6

    thanks,
    mitu

    • Biosopher says:

      Hi Mitu,

      I just download the tutorial and installed it onto my HTC Ion running Android v1.6. It played two different .mp3 without a problem.

      ERROR/com.pocketjourney.media.StreamingMediaPlayer(628): java.lang.NullPointerException

      Judging from this part of your error message though, you’re getting a NullPointerException for some reason. Run debug and let me know what’s causing it.

      • Mitu Kumar Debnath says:

        Hello Biosopher, It’s been a long time I didn’t get here. I was busy with my other works and missed to come here. Still no hope but persist these error logs:

        02-09 18:19:49.754: ERROR/Player(3639): 121544
        02-09 18:19:49.754: ERROR/Player(3639): /data/data/com.pocketjourney.tutorials/cache/playingMedia1.dat
        02-09 18:19:49.944: ERROR/PlayerDriver(51): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported
        02-09 18:19:49.944: ERROR/MediaPlayer(3639): error (1, -4)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): Error initializing the MediaPlaer.
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): java.io.IOException: Prepare failed.: status=0×1
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at android.media.MediaPlayer.prepare(Native Method)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at com.pocketjourney.media.StreamingMediaPlayer.startMediaPlayer(StreamingMediaPlayer.java:170)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at com.pocketjourney.media.StreamingMediaPlayer.access$2(StreamingMediaPlayer.java:159)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at com.pocketjourney.media.StreamingMediaPlayer$2.run(StreamingMediaPlayer.java:143)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at android.os.Handler.handleCallback(Handler.java:587)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at android.os.Handler.dispatchMessage(Handler.java:92)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at android.os.Looper.loop(Looper.java:123)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at android.app.ActivityThread.main(ActivityThread.java:4203)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at java.lang.reflect.Method.invokeNative(Native Method)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at java.lang.reflect.Method.invoke(Method.java:521)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
        02-09 18:19:49.954: ERROR/com.pocketjourney.media.StreamingMediaPlayer(3639): at dalvik.system.NativeStart.main(Native Method)
        02-09 18:19:49.964: WARN/PlayerDriver(51): PVMFInfoErrorHandlingComplete
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.974: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.984: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.984: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.984: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.984: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.994: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.994: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:49.994: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:49.994: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:50.004: ERROR/MediaPlayer(3639): Attempt to call getDuration without a valid mediaplayer
        02-09 18:19:50.004: ERROR/MediaPlayer(3639): error (-38, 0)
        02-09 18:19:50.014: ERROR/MediaPlayer(3639): Error (-38,0)
        02-09 18:19:50.014: ERROR/MediaPlayer(3639): Error (-38,0)

        I tried it with your Tutorials.apk which is provided with your source code. But the same error showing after a 20-30 KB buffering. May be when it is trying to start the media player to play the file.

        Thanks,
        mitu

  16. Mitu says:

    hello Biosopher,
    is there any need of changing in your code for proper media file or need to change the url of media file? here I found that you are changing the extension as *.dat for the media file if I’m correct abt it.

    Please help me from getting out of it.

    Thanks,
    mitu

  17. Biosopher says:

    Hi Mitu,

    Check out roughly the 5th paragraph in this tutorial. It talks about the “PVMFErrNotSupported” error you’re getting.

    As for the .dat extension, it doesn’t matter what you use.

    Anthony

  18. Mitu says:

    Hi Biosopher,

    you were right. This “PVMFErrNotSupported” error is due to FileDescriptor Class. I used file descriptor instead of absolute file path for media player setDataSource() method and it plays for a couple of seconds and then shows these errors: Here it says it doesn’t get the desired file.

    02-10 14:43:14.636: ERROR/Player(848): 122880
    02-10 14:43:14.636: ERROR/Player(848): /data/data/com.pocketjourney.tutorials/cache/playingMedia1.dat
    02-10 14:43:14.816: DEBUG/WifiService(79): ACTION_BATTERY_CHANGED pluggedType: 2
    02-10 14:43:15.847: WARN/AudioFlinger(50): write blocked for 96 msecs
    02-10 14:43:20.046: DEBUG/dalvikvm(501): GC freed 512 objects / 25088 bytes in 201ms
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): Error updating to newly loaded content.
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): java.io.FileNotFoundException: /data/data/com.pocketjourney.tutorials/cache/playingMedia2.dat
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:231)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at java.io.FileInputStream.(FileInputStream.java:80)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at com.pocketjourney.media.StreamingMediaPlayer.transferBufferToMediaPlayer(StreamingMediaPlayer.java:213)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at com.pocketjourney.media.StreamingMediaPlayer.access$3(StreamingMediaPlayer.java:202)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at com.pocketjourney.media.StreamingMediaPlayer$2.run(StreamingMediaPlayer.java:166)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at android.os.Handler.handleCallback(Handler.java:587)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at android.os.Handler.dispatchMessage(Handler.java:92)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at android.os.Looper.loop(Looper.java:123)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at android.app.ActivityThread.main(ActivityThread.java:4203)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at java.lang.reflect.Method.invokeNative(Native Method)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at java.lang.reflect.Method.invoke(Method.java:521)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
    02-10 14:43:31.266: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at dalvik.system.NativeStart.main(Native Method)
    02-10 14:43:31.286: ERROR/MediaPlayer(848): pause called in state 128
    02-10 14:43:31.296: ERROR/MediaPlayer(848): error (-38, 0)
    02-10 14:43:31.306: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): Error updating to newly loaded content.
    02-10 14:43:31.306: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): java.io.FileNotFoundException: /data/data/com.pocketjourney.tutorials/cache/playingMedia3.dat
    02-10 14:43:31.306: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:231)
    02-10 14:43:31.306: ERROR/com.pocketjourney.media.StreamingMediaPlayer(848): at java.io.FileInputStream.(FileInputStream.java:80)

    But if I don’t use file descriptor for setDataSource() method which is inside the transferBufferToMediaPlayer() method then I get these errors:

    02-10 14:57:55.826: ERROR/Player(1003): 122880
    02-10 14:57:55.826: ERROR/Player(1003): /data/data/com.pocketjourney.tutorials/cache/playingMedia1.dat
    02-10 14:57:56.456: WARN/AudioFlinger(50): write blocked for 99 msecs
    02-10 14:58:00.036: WARN/AudioTrack(50): obtainBuffer timed out (is the CPU pegged?) 0x22b78 user=00015ae8, server=00015341
    02-10 14:58:00.036: WARN/AudioTrack(50): *** SERIOUS WARNING *** obtainBuffer() timed out but didn’t need to be locked. We recovered, but this shouldn’t happen (user=00015ae8, server=00015341)
    02-10 14:58:03.766: WARN/AudioTrack(50): obtainBuffer timed out (is the CPU pegged?) 0x22b78 user=0002bd77, server=0002b5d0
    02-10 14:58:03.766: WARN/AudioTrack(50): *** SERIOUS WARNING *** obtainBuffer() timed out but didn’t need to be locked. We recovered, but this shouldn’t happen (user=0002bd77, server=0002b5d0)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): Error updating to newly loaded content.
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): java.io.FileNotFoundException: /data/data/com.pocketjourney.tutorials/cache/playingMedia2.dat
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:231)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at java.io.FileInputStream.(FileInputStream.java:80)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at com.pocketjourney.media.StreamingMediaPlayer.transferBufferToMediaPlayer(StreamingMediaPlayer.java:213)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at com.pocketjourney.media.StreamingMediaPlayer.access$3(StreamingMediaPlayer.java:202)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at com.pocketjourney.media.StreamingMediaPlayer$2.run(StreamingMediaPlayer.java:166)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at android.os.Handler.handleCallback(Handler.java:587)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at android.os.Handler.dispatchMessage(Handler.java:92)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at android.os.Looper.loop(Looper.java:123)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at android.app.ActivityThread.main(ActivityThread.java:4203)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at java.lang.reflect.Method.invokeNative(Native Method)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at java.lang.reflect.Method.invoke(Method.java:521)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
    02-10 14:58:10.906: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at dalvik.system.NativeStart.main(Native Method)
    02-10 14:58:10.956: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): Error updating to newly loaded content.
    02-10 14:58:10.956: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): java.io.FileNotFoundException: /data/data/com.pocketjourney.tutorials/cache/playingMedia3.dat
    02-10 14:58:10.956: ERROR/com.pocketjourney.media.StreamingMediaPlayer(1003): at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:231)

    Here I can see that there is a buffer problem. So what should I do for solve this prob. What do I need to change in codebase.

    Thanks,
    mitu

  19. Biosopher says:

    For some reason you’re getting this error:

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

    That means the newly downloaded content isn’t being written to the new file. Run the app is debug mode with breakpoints during the file writing process to see what’s happening.

    As for not using FileDescriptor during setDataSource(), I can’t tell you what to do. I wasn’t able to get any other option to work properly except FileDescriptor.

  20. Mitu says:

    Hello Biosopher,

    Thank you for helping me. It’s now working.

    Thanks once again :)

    Regards,
    mitu

    • chinmay says:

      Hi Mitu,

      Can you please let me know what did you do in order to remove that error ? I am having the same problem.

      Thanks,
      Chinmay

  21. Biosopher says:

    Hi Tiger,

    This tutorial only supports single files downloads so you must have updated it to support multiple files. Look at how you’re handling the handoff between files. Seems like you are still writing to a file even though no data is being recieved.

    You should only be writing to file what you read from the stream.

    int numread = stream.read(buf);

    out.write(buf, 0, numread);

    Cheers,
    Anthony

  22. Winston says:

    Nice stuff, is it possible to stream live media via real time streaming protocol (rtsp) on android?

    • Biosopher says:

      There appears to be lots of discussion on the web about using RTSP on Android. You could possibly use what’s written here to roll your own rtsp client.

  23. zerayaqob says:

    Thank you so much man, this works like a charm! I’ve been trying to get streaming working for weeks!

  24. [...] in all my searches, which is generally too bad because that’s way out of date (incidentally, here is the newer version). You don’t need to buffer or double buffer media for the media player anymore. However, the [...]

  25. simran says:

    Hi Biosopher,
    We tried playing another audio file as well as a video file with the code you have provided.. It played for 5 sec and then stops playing, but continues to buffer and download the complete file. We guess the problem would be with the number of bytes you assign for two buffers –
    1) the buffer into which the data is copied from the URL. – it is 16384
    2) the buffer used to move the file – it is 8192
    Does these numbers have any significance with the file size or the data rate at which the file is downloaded?

    Do u have an idea if Android emulator 1.5/2.0 supports real-time video streaming?

    • Biosopher says:

      Hi Simran,

      This code was initialy written for Android pre-v1.0. As of Cupcake (v1.5), Android’s MediaPlayer supports streaming video/audio very well.

      • simran says:

        Thanks for the reply.
        We are doing a project where we need to develop the RTP/RTSP stack on Android for real time streaming.

        We are basically receiving the rtp packets for audio/video files over the socket. But we are not able to play them back real-time.

        You mentioned Android’s MediaPlayer supports streaming of video/audio, does this mean real-time support?

        We are referring to the code you have provided for (Cupcake(v1.5)).

        For understanding of the code we tried playing other audio files changing the parameters 16384 and 8192 according to the file size. We couldn’t play the entire file.
        So it would be great if you could just explain the significance of those byte array lengths.

        Thanks in advance.

  26. Biosopher says:

    Hi Simran,

    Android’s MediaPlayer supports very few media types. My code was tested only for .3gp which is a file-based non-real-time audio format.

    My guess is you’re using a file format that isn’t supported by Android. Only these formats are supported:

    http://developer.android.com/intl/zh-CN/guide/appendix/media-formats.html

    • Vipin Sahu says:

      hello Biosopher
      I m aslo using the same code for 2.1 or later but I m required to play MP4 instead only mp3…so I have created surface view and set the display holder for it … also I have to stream the content from SD card rather than any streaming server….

      • Biosopher says:

        Hi Vipin,

        I haven’t had the best of luck displaying mp4 files on Android. 3GP files tend to work best. If you’re playing off the SDCard, then you’re not streaming the video. You’re simply reading a video file off the SDCard. In that case, I recommend 3GP.

  27. Jeremy Coker says:

    Hi Biosopher,

    A related ‘live’ streaming question:

    In my setup I have a live stream source connected which an Axis
    encoder (250S) receives and encodes to MPEG2 which I then receive into
    VLC (re-encodes as h264 – mpeg4) and re-stream out as an RTSP stream, using a .sdp definition.

    I’m attempting to display this LIVE video source using the Media Video
    demo that comes with the Android SDK, i’ve also attempted to use a
    http link in the Android emulator browser.

    But to no avail, I don’t ever see a video playing.

    Can anyone confirm if the android emulator is able to play this type
    of video source and if the
    real android device say an HTC Hero could play this using RTSP.

    OR

    Is there some fundamential thing i’m missing here ?

  28. Jeremy Coker says:

    Mmm… i’m definitely converting this in VLC to h.264 and also tried h.263 format and re-streaming out to android. A second VLC confirms that the live stream plays.

    Only question is can Android really handle a live stream i.e. there is NO file with this except the streaming description file (.sdp)

    The VLC sout configuration for restreaming out to android is:

    :sout=#transcode{vcodec=h264,vb=124,fps=10,scale=1,width=480,height=320,acodec=none}:rtp{dst=10.19.99.129,port=5004,mux=ts,sdp=rtsp://10.19.99.129:8080/stream.sdp}

    ????????

    • Biosopher says:

      Hi Jeremy,

      Unfortunately I’m not experienced enough with live streaming to conclude yea/nay on whether Android can stream live. Given the numerous questions on this tutorial though, it seems Android doesn’t readily support live streaming out of the box.

      Anthony

  29. venkat says:

    Hi Biosopher

    i am using absolute path to play a file which resides in sd card

    mp.reset();
    mp.setDataSource(“/sdcard/playsong.wma”);
    mp.prepare();
    mp.start();

    the following errors are coming up.
    i think its throwing error at mp.prepare();
    could pls help me out??????

    05-13 17:11:15.911: WARN/MediaPlayer(5567): info/warning (1, 26)
    05-13 17:11:15.911: INFO/MediaPlayer(5567): Info (1,26)
    05-13 17:11:15.920: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported
    05-13 17:11:15.930: ERROR/MediaPlayer(5567): error (1, -4)
    05-13 17:11:15.930: WARN/System.err(5567): java.io.IOException: Prepare failed.: status=0×1
    05-13 17:11:15.959: WARN/PlayerDriver(31): PVMFInfoErrorHandlingComplete
    05-13 17:11:15.969: WARN/System.err(5567): at android.media.MediaPlayer.prepare(Native Method)
    05-13 17:11:15.969: WARN/System.err(5567): at com.androplayer1.PlayerService.Playsong(PlayerService.java:92)
    05-13 17:11:15.980: WARN/System.err(5567): at com.androplayer1.PlayerService$1.playFile(PlayerService.java:53)
    05-13 17:11:15.990: WARN/System.err(5567): at com.androplayer1.InterFac$Stub.onTransact(InterFac.java:57)
    05-13 17:11:15.990: WARN/System.err(5567): at android.os.Binder.execTransact(Binder.java:287)
    05-13 17:11:16.000: WARN/System.err(5567): at dalvik.system.NativeStart.run(Native Method)

    • tiger says:

      I’m not Biosopher, but I can see the following in your errors :
      05-13 17:11:15.920: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported

      And I have a very very advanced feature on my mouse : a scrollwheel it’s called.. with that I actually (yes yes) can scroll up and down in a page, that in combination with another very special feature I have (called eyes) I can see this :
      http://blog.pocketjourney.com/2009/12/27/android-streaming-mediaplayer-tutorial-updated-to-v1-5-cupcake/#comment-608

      also you actually might want to read the tutorial itself, and you will notice something about your
      mp.setDataSource(“/sdcard/playsong.wma”);
      code…

      • Biosopher says:

        Thanks Tiger,

        I get rather tired of answering questions for people that are simply too lazy to even read the tutorial.

        Cheers,
        Anthony

  30. hema says:

    can anyone send me code for playing a list of audio mp3 files dat are present in sdcard ………

  31. hema says:

    and also android code to display pdf files pdf files on the emulator……..

  32. arlen says:

    Hi, Thank you for the source code it was gr8
    I have a question,
    How can I stream a radio station via android insted of streaming mp3 files .
    something like this one :

    http://mfile.akamai.com/2110/live/reflector:20637.asx?bkup=21011
    .asx file types.

  33. arlen says:

    hi ,
    Is there any direct link that I can download all the MyNPR or npr files like a zip file ?

  34. Biosopher says:

    Hi Nissar,

    To pre-allocate the memory, create a File on the SD Card and write your desired number of bytes to it. You can set the saved bytes to whatever value you want.

    • Nissar says:

      <<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>
      <<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

      Hi Biosopher,
      Thank you for your quick reply.
      But, What you told is to fill the space with dummy bits(as i mentioned in the question). Is there any other way for this.
      Because I’m maintaining a download queue. So the number of files downloading can be more than one(it can’t be pre-calculated). If I create a file with dummy bits filled, after dowloading the files in queue to a single file, I have to partition it(it can be done). What I need is just lock the SDCard blocks(say i’m reserving 100MB for downloading). I hope you understood what I meant.
      Thank you very much.

  35. ruslan says:

    Hi! I can’t download the source file from your link http://www.pocketjourney.com/downloads/pj/tutorials/tutorials_1.5.zip

    Could you be so kind as to send me the file, please!

  36. Hi,

    Just one question. Why you can’t just use an AsyncTask together with MediaPlayer instead of managing all threads and updates manually?

    Thank you.

    • Biosopher says:

      I totally agree, Andrey. This code was originally written in Android 1.4 and wasn’t updated to AsyncTasks which first became available in 1.5.

      If you port the code to AsyncTask, let me know and I’ll link to it.

  37. Javanator says:

    i need to know the total duration of song so that i can set the Progress Bar accordingly. As soon my Media Player starts playing the song. I call

    mediaPlayer.getDuration() for getting the file duration .. But it is not giving me the right data untill the whole song get downloaded….

    This is bad . as it seems getDuration() Method of MediaPlayer is showing the duration on the basis of downloaded content instead of checking the header of Mp3 file…..

    Any Help would be appreciated. Thanks

  38. Biosopher says:

    Hi Javanator,

    I don’t recall if the durection is available from the .mp3 header. I think it has to do with the file size and bit rate. Don’t have the code in front of me at the moment. In either case, you can see where the duration is being calculated by looking through the code.

    Biosopher

    • Biosopher says:

      durection=duration… :-) I recall that the duration is actually calculated from the file size provided during download initiation.

  39. Chris says:

    I’m trying to stream a raw AAC stream from a site. I used the buffering technique provided in the tutorial, which works great in all of my emulators, however it’s not working on a single real device. It just hangs forever.

    I haven’t checked any logcats yet, but does anyone have an idea what could be going wrong here?

    Thanks.

  40. Anudeep says:

    Hi All,

    I downloded the code and installed the apk file in my phone. It starts reading (Streaming), but once it completes reading it does not play the file.

    Please Help me with this issue.

  41. Kenneth Roy says:

    Anyone find a solution to the gap problem yet? I’ve tried the StreamingMediaPlayer and the myNPR versions, but both still have gaps. The reason I need this working is because I need to access a stream that requires authentication and I have not been able to find a way to do this with the MediaPlayer.

    • Biosopher says:

      It’s unclear to me why anyone would be having issues with gaps. As the tutorial code is written, it’s simply incrementally downloading a file from the server. I.e., the code is written to read a single ‘finite’ audio file from the server NOT to download some type of continuous stream of audio. The only data written to the hard disk should be data sent by the server which should only be the contents of the audio file as present on the server’s disk…thus no gaps.

      Have you altered the code in some way or are you downloading an actual audio stream?

      • Ken says:

        Yes, I am trying to download an actual audio stream. And yes, I know that your code was designed originally for single, finite audio files, but I have not found any other way of playing an audio stream that requires authentication. I merely used this code as a starting point to see if I could tweak it to work with audio streams instead of files.

        At this point I am able to authenticate with the server and get the audio stream to play in the MediaPlayer, but I have not been able to remove the skips that occur when sending the buffered audio stream to the MediaPlayer. That is, the code currently stores a few seconds of the stream in the cache and then sends that to the MediaPlayer and then repeats this process.

        I’ve attempted the multiple-MediaPlayer-type solution in the myNRL code, but that still causes skips.

        I’ve also tried http://username:password@url and http://url?username&password as well, but they are not working with MediaPlayer. I’m assuming the MediaPlayer is not parsing these correctly.

        And I’ve tried creating an “Authenticator” as well, which did not work either.

        So do you have any ideas on how one could play a stream that requires authentication?

  42. rockin says:

    its works fine….but the progress bar ends bfor the song ends

    • Biosopher says:

      There may be two progress bars. One for the audio download progress and the other for the file playback progress. Are you seeing both or just one?

  43. Biosopher says:

    Hi Ken,

    Great to hear people are finding new uses for this code. I hadn’t intended it for playing streaming audio but seems many many people are having the same problme.

    What audio stream format are you receiving? According to Android’s website, support is available for:

    http://developer.android.com/guide/appendix/media-formats.html

    •RTSP (RTP, SDP)
    •HTTP progressive streaming
    •HTTP live streaming draft protocol (Android 3.0 and above)

    A quick search says some HTTP streaming servers set the content type is a way that confuses Android. Do you know which content type is showing in your stream’s header?

    http://stackoverflow.com/questions/1965784/streaming-audio-from-a-url-in-android-using-mediaplayer

    • Kenneth Roy says:

      There are two streams that I wish to play. Both are setup at the server the exact same way (shoutcast/ICY/MP3/http). However, one requires a username/password and the other does not.

      The stream that does not require a username/password streams just fine using MediaPlayer.

      The stream that does require a username/password will not work with MediaPlayer. I’ve tried using an Authenticator and also putting the username/password into the URL (see previous post).

      I am not convinced that the problem is how the streams are configured. I am able to play the stream that requires a username/password in my iPhone version of the app. But what happens on the iPhone is: 1) attempt to connect to URL 2) receive request to authenticate 3) send credentials 4) receive stream.

      There doesn’t appear to be a way using MediaPlayer to authenticate.

      I am able to authenticate using a URLConnection with an Authenticator (I added the Authenticator to your code to accomplish this). So obviously it is possible on the Android to authenticate. However the MediaPlayer just does not use the Authenticator.

      Does this make sense?

  44. 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

  45. 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)

  46. mimi says:

    hi Biosopher,

    First of all, thank you so much for this tutorial, it helps me a lot!!!!
    I’m new in developing Android applications and I’ve got a little problem :

    My first activity is a listview of 8 radio stations from a website.
    My second activity is your tutoriel , the streaming works for each radio stations.

    My problem is that I want to stop automatically the previous radio station when I load another radio.

    I’ve got 2 activities and my class StreamingMediaPlayer. I work on Eclipse 1.4.

    Anyone have an idea?

    Thanks very much

  47. Carel says:

    hi all,
    First of all I’m not a programmer but I have mobile sites made for me; I have this question about sound files. I like to post 5 sound files of about 1min each on a mobile website. Viewers of my site should be able to listen to these sound files, also with ‘older’ smart phones (ie. eg. Android 1).

    My programmers in India told me that this is only possible with Flash, however I always learned that Flash is a no-brainer for mobile.

    Are there any solutions for this?

    Thanks.
    Carel

  48. Biosopher says:

    If you’re streaming from a mobile website, then Flash is probably a better option. This blog post is about streaming audio to an Android application installed off the Android Market.

  49. Carel says:

    @Biosopher — thanks for your swift reply; I thought that one should not use Flash based elements (ie. music/video); Apple/Iphone is not even supporting Flash isn’t?

  50. Carel says:

    Thanks for your swift reply Biosopher; I thought though that Flash was not a good thing to use (Apple/Iphone is not supporting this do they?), so is there an alternative?

    • Biosopher says:

      Hi Carel,

      You’re right. Flash doesn’t work on the iphone and runs slow on Android. For the iPhone, simply add a link to the .mp3 file on your webpage. When the user clicks the .mp3 files, the iPhone will launch the phone’s media player.

      I believe for Android, the user must press and hold the link until a menu pops up and select “Save Link”. This should then download the .mp3 file for you and you will be able to play it.

  51. Antoine says:

    Hi,

    This tutorial is very good and useful I can’t wait for studying it.
    Unfortunately I can’t download the archive file in order to have sources.
    Can you make it available ?

    Thank you in advance ! And also for this tutorial :)

  52. Steph says:

    I am loving all the tutorial files, they are really helping my learning curve.

    Is there any way that the tutorials could be split into their individual tutorials rather than joined?

  53. Jordy says:

    This looks really nice, i’d also like to download the source code but the server seems to be down?

  54. [...] Android Streaming MediaPlayer Tutorial – Updated to v1.5 (Cupcake) « Pocket Journey [...]

  55. [...] to do this? I use this documentation MediaPlayer | Android Developers And I also found this: Android Streaming MediaPlayer Tutorial – Updated to v1.5 (Cupcake) Pocket Journey but non of them help to recover the position where you was downloading… Hope some of you know [...]

  56. [...] #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 [...]

  57. Jip-Hop says:

    Dear Biosopher,

    thanks a ton for writing this tutorial, this is exactly what I’m looking for.
    I’ve checked out the tutorial for Android v1.0 and installed the proved .apk to test the app without modifying anything. It starts streaming and playing just fine. But after a few seconds, playback stops (but the download continues shown by the progressbar and “Audio full loaded: 1717 Kb read”). I’m still to figure out where the file is exactly being saved though, just to verify it full downloads.

    My guess is that it fails at this part: “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.”

    In this article you write that “MediaPlayer.setDataSource() now takes a FileDescriptor instead of a String path to the media File.” So I thought the problem I’m having would be fixed by updating to the version from this article.

    I downloaded your source files, installed the .apk that has been updated for Android v1.5 but it didn’t work at all. When I hit the “Start Streaming” button, it remains in a pushed down and greyed out state. It never pops back up, no progress bars show up and no sound is being played. I didn’t modify anything and I’m running this app on my Samsung Galaxy Note N7000 with Android 4.1. Do you know what’s wrong?

    I have another question:
    You write in a reply “I’m fairly happy with the built-in streaming of v1.5 so I don’t use my own code anymore.” I’m glad you are happy :) For me, the main reason I’m interested in your solution is this aspect: “We store the streamed audio locally so you could cache it on device for later use”, as written in your previous article. I’d like to stream an mp3 file initially and simultaneously store it on the SD card. The next time I want to play the file, it will be loaded from the SD card. The mp3 will be downloaded just once. If you are not using your own code any more, how do you handle this particular scenario?

    • Jip-Hop says:

      Okay, I was in the train the other day and couldn’t really test beyond running the downloaded apk. There was nothing wrong with the code, just that the mp3 file is down. I tested with one of my own and it works excellently :)

      My second question remains though.

      • Biosopher says:

        Hi Jip-Hop,

        Just back from an Internet-free vacation. Did you solve your problem with caching the file? Sadly I don’t think the MediaPlayer built into Android supports caching…thought perhaps it could be extended to do so.

  58. This code is really work. But I got the error “error(1,-4)” when using the above url:-

    https://ibharati-radio.s3.amazonaws.com/production/uploads/song_upload/file/2/Yeh_Jo_Halki_Halki_Khumariya.mp3

    will you please help me???
    Please give me solution for that.

    Thanks in advance.
    Shailesh

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>