http://blog.pocketjourney.com/2008/04/04/tutorial-custom-media-streaming-for-androids-mediaplayer/
Tags: Android, audio, google, media, mediaplayer, stream, tutorial, video
Pocket Journey
Know Anywhere
Android Tutorial 3: Custom Audio Streaming with MediaPlayer
Published April 4, 2008 Android , Tutorials 241 CommentsTags: Android, audio, google, media, mediaplayer, stream, tutorial, video
Introduction
NOTE: 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.
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:

Basic Layout
The tutorial consists of just two classes:
Start Your Streaming
Upon clicking the “Start Streaming” button, Tutorial3 creates an instance of StreamingMediaPlayer.
Tutorial3 then calls StreamingMediaPlayer.startStreaming():
AudioStreamer.startStreaming() creates a new thread for streaming the content so we can immediately return control back to the user interface.
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:
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.
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.
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.
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.
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
NOTE: 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.
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:
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.StreamingMediaPlayer: Connects to the server, downloads audio into the buffer, and controls the functionality to ensure the audio continues to play seamlessly.
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;
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;
return;
}
}
};
new Thread(r).start();
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:(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.
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) {
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);
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 {
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0) {
if (numread <= 0) {
// Nothing left to read so quit
break;
break;
} else {
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
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();
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();
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() {
// 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) {
// 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);
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();
// 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);
handler.post(updater);
}
Starting the MediaPlayer with Initial Content BufferStarting 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) {
FileUtils.copyFile(downloadingMediaFile,bufferedFile);} catch (IOException e) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());
mediaPlayer.prepare();
fireDataPreloadComplete();
mediaPlayer.setDataSource(bufferedFile.getAbsolutePath());
mediaPlayer.prepare();
fireDataPreloadComplete();
Log.e(getClass().getName(), “Error initializing the MediaPlaer.”, e);
return;
return;
}
}
Transferring Buffered Content to a MediaPlayer That is Already PlayingThis 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();
// 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);
// 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);
// 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){
// 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);
}
}
ConclusionTo 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.
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
241 Responses to “Android Tutorial 3: Custom Audio Streaming with MediaPlayer”
- 1 Trackback on April 30, 2008 at 5:14 pm
- 2 Trackback on May 2, 2008 at 12:13 pm
- 3 Trackback on August 11, 2008 at 9:51 pm
- 4 Trackback on August 7, 2009 at 3:51 am
- 5 Trackback on August 9, 2009 at 12:02 am
- 6 Trackback on December 27, 2009 at 9:30 am
- 7 Trackback on April 25, 2010 at 9:12 am
- 8 Trackback on October 25, 2010 at 4:16 pm
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();
}
}
could you tell me how does pv player comes into picture while creating a media player application.
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
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
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:\personal\Work\Code\Eclipse\MobileJourney\bin\MobileJourney.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
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
I forget to mention that I am using windows XP.
souvik
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
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
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));
}});
}
}
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
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 ….
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 …
continued in next blog ….
Can u please modify the code to make me understand!!
Thanks,
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
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
Simply call: startActivity(new Intent(this, YourActivity.class));
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
How to refresh R.java file if its not updating automatically when I am adding one file in resource?
Thanks,
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
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
I was wondering if you could provide a sample code of how u created the media player as a service?
thanks!
anu
FileUtils were supported in the earlier version .but not in 1.0
how to solve this problem?
thanks
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() );
}
}
11-19 16:00:06.659: ERROR/MediaPlayer(536): Error (-38,0)
Whats the reason for this error??
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)
p.s
I could be wrong of course but it is my observarions
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
player cannot read user’s files.
use:
FileInputStream ins = new FileInputStream(bufferedFile.getAbsolutePath());
mediaPlayer.setDataSource(ins.getFD());
instead
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
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 ?
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
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) {
}
});
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
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
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.
I am doing this to setDataSource:
FileInputStream ins = new FileInputStream(bufferedFile.getAbsolutePath());
mediaPlayer.setDataSource(ins.getFD());
Any ideas?
-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
Thanks.
amit
Anthony
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!
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
Are you aware of anything that can help me play streaming or progressive download video content, without downloading the whole file first?
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);
}
}
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();
}
}
}
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
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
Video stream in ApiDemos is not working showing java exceprion error after mediaplayer.prepare()
Thanks,
Geetha
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
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
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
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?
Thanks
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
http://www.pocketjourney.com/downloads/pj/video/famous.3gp
As amit suggests, this works in API Demo’s MediaPlayerDemo_Video class:
http://www.pocketjourney.com/downloads/pj/video/famous.3gp
Cheers,
Anthony
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
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
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
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
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
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
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
Can anyone tell me how to stream live videos on android emulator?
Kindly help as this is very urgent!!!
REgards,
Aahan
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
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
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
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
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
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
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!!!
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
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
Your or anybody’s reply on this would be great help.
Thanks,
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
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
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
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
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
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
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
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
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…
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
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
Can we able to encode the video file url through code to make it to support streaming in android…?
thanks,
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
is this player also able to play aac streams ?
Thanks for the reply. Can we have any other way of converting the video file to streaming format other than QuicktimePro..?
thanks ,
Senthil.M
This tutorial uses Android’s MediaPlayer so it would work with any format supported by Android.
Anthony
I’m sure there are but I found that Quicktime Pro worked and stooped looking after that.
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
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
Anthony
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 ?
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.
Senthil.M
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
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
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
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
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
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
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
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
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
If you close the FileOutputStream first, then is will prepare and play.
At least that is my experience.
It is not perfect though.
http://code.google.com/p/mynpr/source/browse/trunk/mynpr/src/com/webeclubbin/mynpr/StreamingMediaPlayer.java?spec=svn9&r=9
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
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
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
Thanks a lot, the v1.5 code works! And no error occur!
thanks again
Monkey
Anthony
Streaming Media: http://blog.pocketjourney.com/2009/12/27/android-map-tutorials-updated-to-v1-5-cupcake-mapview-mapactivity Maps: http://blog.pocketjourney.com/2009/12/27/android-streaming-mediaplayer-tutorial-updated-to-v1-5-cupcake
Cheers, Anthony
Streaming Media: http://blog.pocketjourney.com/2009/12/27/android-map-tutorials-updated-to-v1-5-cupcake-mapview-mapactivity/
Maps: http://blog.pocketjourney.com/2009/12/27/android-streaming-mediaplayer-tutorial-updated-to-v1-5-cupcake/
Cheers,
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
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?
http://www.pocketjourney.com/downloads/pj/video/famous.3gp
With this url also, it is not working in 2.0.1 version emulator.
thanks,
Senthil.M
ERROR/SurfaceFlinger(64): layer 0×3f8528, texture=2, using format 32, which is not supported by the GL
And this message is repeated till the end of the video play. Simply getting a white screen in the view. But audio is working fine. I found some links related to this issue posted by some people. I am attaching those links here below.
http://groups.google.com/group/android-developers/browse_thread/thread/9081b2f56654ec7/5c8ccb3fb06dd4e4#5c8ccb3fb06dd4e4
http://stackoverflow.com/questions/1855246/android-videoview-video-not-seen/1973723#1973723
Also i have posted this issue in android bug tracker site which can be referred here.
http://code.google.com/p/android/issues/detail?id=5696#makechanges
thanks,
Senthil
ERROR/SurfaceFlinger(64): layer 0×3f8528, texture=2, using format 32, which is not supported by the GL
And this message is repeated till the end of the video play. Simply getting a white screen in the view. But audio is working fine. I found some links related to this issue posted by some people. I am attaching those links here below.
http://groups.google.com/group/android-developers/browse_thread/thread/9081b2f56654ec7/5c8ccb3fb06dd4e4#5c8ccb3fb06dd4e4
http://stackoverflow.com/questions/1855246/android-videoview-video-not-seen/1973723#1973723
Also i have posted this issue in android bug tracker site which can be referred here.
http://code.google.com/p/android/issues/detail?id=5696#makechanges
thanks,
Senthil
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.
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?
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);
}
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 ?
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.
But still there is gap in between switching over of files
What will be the workaround for that????
Please tell me solution.
Thanks
Kavitha
I just tested the streaming tutorial and don’t hear any gaps in the downloaded audio.
Anthony
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.
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();
}
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?
I tried with mp.stop() and mp.release().
Still it is same.
Any other alternatives????
or else do you have any idea of converting audio to PCM and playing from AudioTrack class of Android?
kavitha
you will try mp.reset();
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??
You should read all the responses to this current post as dozens of people have already asked that question and posted many answers.
Also read this post for the same reason: http://blog.pocketjourney.com/2009/12/27/android-map-tutorials-updated-to-v1-5-cupcake-mapview-mapactivity/
How to implement media player as service.
Please suggest.
Thanks
Kavitha
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.
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 ^^
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.
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?
Do you see any error messages in the Log?
Anthony
Where can I see the log messages in the emulator? Kindly guide me, I will check and get back to you.
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.
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)
It looks like you altered the tutorial code slightly. Read the tutorial section for information about “PVMFErrNotSupported”.
Anthony
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
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?
It is not so bad now. I used this page to help with my npr app doing live streaming. Since the current mediaplayer would not stream shoutcast-like live streams. I do hear the audio gaps but people Using the app dont seem to mind. Or maybe they cant tell?
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
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!!!
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.
What radio station are you streaming and what format is their stream encrypted into?
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
Abhijeet
So you only send me the required files to run it. My id is:-
abhijeetpatna2008@gmail.com
Abhijeet
So you only send me the required files to run it. My id is:-
abhijeetpatna2008@gmail.com
Abhijeet
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
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
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 !!!!
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
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
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
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…
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
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?
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
I have used this code but it is not streaming audio.Will this code work on android emulator.
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
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
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…
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.
Sounds like the website is using Flash…which is not supported on the iPhone.
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.
I don’t know anything about shoutcast streams. Most likely it is a streamed media format. Android provides little support for streaming formats.
Anthony
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.
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
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.
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
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
Checkout the updated post here as well:
http://blog.pocketjourney.com/2009/12/27/android-streaming-mediaplayer-tutorial-updated-to-v1-5-cupcake/
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
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
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.
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…
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
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;
}
}
}
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
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
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.