| Android Tutorial 3: Custom Media Streaming with MediaPlayer |
|
|
|
|
Introduction This is a long tutorial, but for those of you that have been struggling with streaming of media 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 media 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:
Basic Layout The tutorial consists of just two classes: Tutorial3: Contains
the UI layout and process button clicks 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.
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; Runnable r = new Runnable() { public void run() { try { downloadAudioIncrement(mediaUrl); } catch (IOException e) { Log.e(getClass().getName(), “Initialization
error for fileUrl=” + mediaUrl, e); } } }; } 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. 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 Log.e(getClass().getName(), “Unable to create InputStream for mediaUrl:” + mediaUrl); } // Create
the temporary file for buffering data into // Start
reading data from the URL stream int numread = stream.read(buf); // Nothing
left to read so quit } else { out.write(buf, 0, numread); // Test whether
we need to transfer buffered data to the MediaPlayer } } while (true); // Lastly
transfer fully loaded audio to the MediaPlayer and close the InputStream } 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 causes crashes to we always ensure we are interacting 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 public void run() { if (mediaPlayer == null) { // The
MediaPlayer has not yet been created so see if we have try { // We have
enough buffered content so start the MediaPlayer } 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 } } }; } Starting the MediaPlayer with Initial Content Buffer Starting the MediaPlayer is very straightforward now. We simply
copy all the currently buffered content private void startMediaPlayer(File bufferedFile) { try { File bufferedFile = File.createTempFile(”playingMedia”,
“.dat”); mediaPlayer = new MediaPlayer();
Log.e(getClass().getName(), “Error initializing
the MediaPlaer.”, e); } } 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 // Copy
the current buffer file as we can’t download content into the same file that // Create
a new MediaPlayer. We’ve tried reusing them but that seems to result in // Restart
if at end of prior beuffered content or mediaPlayer was previously playing. 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.
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.
Source: http://blog.pocketjourney.com/2008/04/04/tutorial-custom-media-streaming-for-androids-mediaplayer/ Comments (6)
![]() creating custom user login forms with user authentication
written by jane , December 01, 2009 a code snippet on above would help
report abuse
vote down
vote up
Votes: -1
...
written by jane , December 01, 2009 code snippet to perform user authentication will help
report abuse
vote down
vote up
Votes: -1
ugg boots
written by uggs outlet , January 18, 2010 Many womenswear trends ultimately cross over to the men's market, but not all. Take the Ugg boot. Ugg is really punting its footwear in uggs outlet the direction of gentlemen – motorbike boot-style Uggs, rugged waterproof Uggs – but we're not biting.
It can't be a matter of effeminacy; they're meant to be unisex. Those who first favoured the wool-lined sheepskin boot were not only men, but men of a macho stripe befitting footwear seemingly named after the main ugg boots for sale conversational gambit of the caveman: first world war aviators and sheep-shearers in rural Australia. report abuse
vote down
vote up
Votes: +0
...
written by ugg boots for sale , February 09, 2010 Nike Air yeezy
report abuse
vote down
vote up
Votes: +0
Write comment
|
The names (identifiers) in your xml file for the buttons are different to the ones in your java code (e.g. PlayButton and button_play). In fact, most of them are wrong from what I remember.
There were some other errors in your code from what I remember (sorry I can't remember which, I know that's not very usefull!
You've also got the line:
android:src="http://whyandroid.com/components/com_jomcomment/templates/default/@drawable/button_pause"/>
in the
I've been going through it and sorting it out for my own use. But I've come to another problem. Android SDK version is now at 1.5. I think your programming may be for 1.0 ?? Anyway, since then, you cannot use 'import android.os.FileUtils;' because it no longer exists!!
Do you know what the alternative, as I have no idea!!
Your tutorial has been helpful, but also a little confusing for a beginner like myself!
Oh ..... I think the link at the top of your page labeles 'source code' may link to a different to the one at the bottom as well, because I'm pretty sure the xml file in the one at the top had no mention of the progress bar. The labeles are wrong in both files though.
Hope this helps in someway.
Andy