Live video streaming application on Android - android

I am trying to build a live video streaming application that streams live video from Android.
Using the MediaRecorder class, I am able to capture the video data in the form of 3gp, with h263 codecs.
However, when I run my application and stream media, I get a 2-3 second delay at the server side.
Why am I getting this delay? Are there any internal buffers that I need to flush? Are there other ways of streaming video apart from using MediaRecorder class?

If you're set on RTMP streaming from Android, the best solution is MediaCodec + FFmpeg + librtmp. This avoids any hacky "detect the NAL Unit within the bytestream" business but requires Android 4.3. Skate where the puck is going...
I've developed an open source SDK that demonstrates RTMP streaming with FFmpeg + librtmp as pre-built shared libraries. The SDK is focused on HLS streaming, but RTMP support is present.
If you'd like help building FFmpeg yourself for Android (with or without librtmp), check out my guide.

If the Android app works well, and the code it's optimitzed, provably the reason of that delay is that you are seding heavy data to server and the HTTP request to a server have a limit of MB to be send. When that happends the class automaticly or the programer must fractionate the HTTP request to multiple HTTP requests and obviously it's slower.

first create this class.
MediaPlayerDemo_Video.java:-
package com.videostreaming.player;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
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 MediaPlayerDemo_Video extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private String path1 = "http://podcast.20min-tv.ch/podcast/20min/199733.mp4";
// private String path2 = "http://podcast.20min-tv.ch/podcast/20min/199752.mp4";
private String path2 = "http://podcast.20min-tv.ch/podcast/20min/199693.mp4";
private String path = "";
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 Bundle extras;
private static final String MEDIA = "media";
private static final int LOCAL_AUDIO = 1;
private static final int STREAM_AUDIO = 2;
private static final int RESOURCES_AUDIO = 3;
private static final int LOCAL_VIDEO = 4;
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private Bundle bdlReceivedData = null;
private Intent self = null;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
self = this.getIntent();
bdlReceivedData = self.getExtras();
if (bdlReceivedData != null && bdlReceivedData.getInt("video") > 0)
{
if (bdlReceivedData.getInt("video") == 1)
{
Toast.makeText(MediaPlayerDemo_Video.this,"playing Video 1", Toast.LENGTH_SHORT);
path = path1;
}
else if (bdlReceivedData.getInt("video") == 2)
{
Toast.makeText(MediaPlayerDemo_Video.this,"playing Video 2", Toast.LENGTH_SHORT);
path = path2;
}
}
}
private void playVideo(Integer Media) {
doCleanUp();
try {
// switch (Media) {
// case LOCAL_VIDEO:
// /*
// * TODO: Set the path variable to a local media file path.
// */
// path = "";
// if (path == "") {
// // Tell the user to provide a media file URL.
// Toast
// .makeText(
// MediaPlayerDemo_Video.this,
// "Please edit MediaPlayerDemo_Video Activity, "
// + "and set the path variable to your media file path."
// + " Your media file must be stored on sdcard.",
// Toast.LENGTH_LONG).show();
//
// }
// break;
// case STREAM_VIDEO:
// /*
// * TODO: Set path variable to progressive streamable mp4 or
// * 3gpp format URL. Http protocol should be used.
// * Mediaplayer can only play "progressive streamable
// * contents" which basically means: 1. the movie atom has to
// * precede all the media data atoms. 2. The clip has to be
// * reasonably interleaved.
// *
// */
// path = "";
// if (path == "") {
// // Tell the user to provide a media file URL.
// Toast
// .makeText(
// MediaPlayerDemo_Video.this,
// "Please edit MediaPlayerDemo_Video Activity,"
// + " and set the path variable to your media file URL.",
// Toast.LENGTH_LONG).show();
//
// }
//
// break;
//
//
// }
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
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 onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
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");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
}
#Override
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();
}
}
now the next class
MainMenu.java
package com.videostreaming.player;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainMenu extends Activity {
Button btn_videoViewDemo1;
Button btn_videoViewDemo2;
Button btn_MediaPlayerDemo1;
Button btn_MediaPlayerDemo2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_videoViewDemo1 = (Button)findViewById(R.id.btn_videoViewDemo1);
btn_videoViewDemo2 = (Button)findViewById(R.id.btn_videoViewDemo2);
btn_MediaPlayerDemo1 = (Button)findViewById(R.id.btn_MediaPlayerDemo1);
btn_MediaPlayerDemo2 = (Button)findViewById(R.id.btn_MediaPlayerDemo2);
btn_videoViewDemo1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Navigation1 = new Intent(MainMenu.this,streamplayer.class);
Navigation1.putExtra("video",1);
startActivity(Navigation1);
}
});
btn_videoViewDemo2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Navigation1 = new Intent(MainMenu.this,streamplayer.class);
Navigation1.putExtra("video",2);
startActivity(Navigation1);
}
});
btn_MediaPlayerDemo1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Navigation1 = new Intent(MainMenu.this,MediaPlayerDemo_Video.class);
Navigation1.putExtra("video",1);
startActivity(Navigation1);
}
});
btn_MediaPlayerDemo2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent Navigation1 = new Intent(MainMenu.this,MediaPlayerDemo_Video.class);
Navigation1.putExtra("video",2);
startActivity(Navigation1);
}
});
}
}
streamplayer.java
package com.videostreaming.player;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class streamplayer extends Activity {
/** Called when the activity is first created. */
private String path1 = "http://podcast.20min-tv.ch/podcast/20min/199733.mp4";
//private String path2 = "http://podcast.20min-tv.ch/podcast/20min/199752.mp4";
private String path2 = "http://podcast.20min-tv.ch/podcast/20min/199693.mp4";
private String path = "";
//// Method 1 - Default Method
private VideoView mVideoView;
private Bundle bdlReceivedData = null;
private Intent self = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.videoview);
mVideoView = (VideoView) findViewById(R.id.surface_view);
self = this.getIntent();
bdlReceivedData = self.getExtras();
if (bdlReceivedData != null && bdlReceivedData.getInt("video") > 0)
{
if (bdlReceivedData.getInt("video") == 1)
{
Toast.makeText(streamplayer.this,"playing Video 1", Toast.LENGTH_SHORT);
path = path1;
}
else if (bdlReceivedData.getInt("video") == 2)
{
Toast.makeText(streamplayer.this,"playing Video 2", Toast.LENGTH_SHORT);
path = path2;
}
/*
* Alternatively,for streaming media you can use
* mVideoView.setVideoURI(Uri.parse(URLstring));
*/
//mVideoView.setVideoPath(path1);
///ELSE
mVideoView.setVideoURI(Uri.parse(path));
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
mVideoView.postInvalidateDelayed(100);
mVideoView.start();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(streamplayer.this,"Error Occured:- " + e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
mediaplayer_2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
videoview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="#+id/surface_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"/>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"/>
<Button
android:id="#+id/btn_videoViewDemo1"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:text="VideoView1"
android:layout_margin="10dip">
</Button>
<Button
android:id="#+id/btn_videoViewDemo2"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:text="VideoView2"
android:layout_margin="10dip">
</Button>
<Button
android:id="#+id/btn_MediaPlayerDemo1"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:text="MediaPlayerDemo1"
android:layout_margin="10dip">
</Button>
<Button
android:id="#+id/btn_MediaPlayerDemo2"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:text="MediaPlayerDemo2"
android:layout_margin="10dip">
</Button>
</LinearLayout>

Related

How to Stream TV channel into your Android application?

I have been streaming videos on my Android App that are on Server But I want to Stream videos that are currently running on the TV
channels as live.
If there is any way i can run live videos of TV channels into my Android App, please guide me.
I have used this URL http://blindy.tv/all.m3u to stream video but when it runs I got error, that This video can not be played.
I think this URL is fine, but my application is not able to play videos, like fetch video and then play continuously as this url is
streaming videos.
I have an assignment to show videos of a TV channel into Android App.
How can i show it.?
My Code is Following that is working fine for some video that is placed on server. but i want my code to work to display live tv
channels streaming in my android app. How can i do this as to cover my
Assignment ???
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class Main5Activity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "TAG";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/*OnCreate() function */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/*playVideo() function */
private void playVideo() {
doCleanUp();
try {
path = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
if (path == "") {
// Tell the user to provide a media file URL.
Toast.makeText(
this,
"Please edit MediaPlayerDemo_Video Activity,"
+ " and set the path variable to your media file URL.",
Toast.LENGTH_LONG).show();
}
Log.e("PATH", "Path = " + path);
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepare();
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
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 onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
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");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#Override
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;
}
/*startVideoPlayback() function */
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}

How do I play a live HTTP audio stream in MediaPlayer on Android?

I want to play a live HTTP stream in my Android app, so I installed the Windows Media Encoder 9 on another PC on the same LAN, and used it to create a live HTTP audio stream.
The live HTTP stream is okay: I tested it, and it can be played by Windows Media Player or VLC on a PC, and can be played by VLC for Android on my mobile.
So, in my Android app, I wrote this code:
private MediaPlayer player = null;
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
//.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button)findViewById(R.id.play);
address = (TextView)findViewById(R.id.address);
btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
play();
}
});
}
private void play()
{
String serverIp;
serverIp = address.getText().toString(); // get the uri address, for example http://xxx.xxx.xxx.xxx:2340
if (player == null)
{
player = new MediaPlayer();
}
else
{
player.stop();
player.reset();
}
try {
Log.v("", "Init a new MediaPlayer");
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.v("", "Set the stream type to STREAM_MUSIC");
player.setDataSource(this, Uri.parse(serverIp));
Log.v("", "Set the source is " + serverIp);
player.setOnBufferingUpdateListener(this);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.prepareAsync();
Log.v("", "After prepareAsync");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.v("IllegalArgumentException", e.toString());
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.v("SecurityException", e.toString());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.v("IllegalStateException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("IOException", e.toString());
} catch (Exception e) {
Log.v("Exception",e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
Log.v("onPrepared", "After prepareAsync");
mp.start();
}
catch (Exception e) {
Log.v("play", e.toString());
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
Log.v("onBufferingUpdate", "Buffering Update");
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.v("MediaPlayer onError", "what=" + what + " extra=" + extra);
return true;
}
But it didn’t work. When I click the play button, nothing happens. But if I input some other URL I found on the internet (for example, http://www.example.com/song.mp3), it works.
So can anyone help me? The Log info is below. My mobile is HTC s710e, and my Android version is 4.0.4.
11-20 22:28:14.137: V/(580): Init a new MediaPlayer
11-20 22:28:14.137: V/(580): Set the stream type tp STREAM_MUSIC
11-20 22:28:14.147: D/MediaPlayer(580): Couldn't open file on client side, trying server side
11-20 22:28:14.178: E/Trace(39): error opening trace file: No such file or directory (2)
11-20 22:28:14.178: V/(580): After prepareAsync
11-20 22:28:14.297: V/ChromiumHTTPDataSource(39): connect on behalf of uid 10044
11-20 22:28:14.339: I/qtaguid(39): Tagging socket 27 with tag 3f500000000(1013) for uid 10044 failed errno=-2
11-20 22:28:14.629: I/ChromiumHTTPDataSourceSupport(39): Server responded with http status 400
11-20 22:28:14.648: I/qtaguid(39): Untagging socket 27 failed errno=-2
11-20 22:28:14.657: I/AwesomePlayer(39): mConnectingDataSource->connect() returned -1004
11-20 22:28:14.657: E/MediaPlayer(580): error (1, -1004)
11-20 22:28:14.667: E/MediaPlayer(580): Error (1,-1004)
11-20 22:28:14.667: V/MediaPlayer onError(580): what=1 extra=-1004
you can play HLS on android 3.0and 3.0 + version, older versions doesnt support HLS. This code below, can work on 3.0 + version. To play video all android version you have to use rtsp streaming or http prograssive download.
Player class
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
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;
public class VideoPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, 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 Bundle extras;
private static final String MEDIA = "media";
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.VideoView);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
path = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
//mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
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 onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
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");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(STREAM_VIDEO);
}
#Override
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();
}
}
Main XML
<VideoView
android:id="#+id/VideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:layout_weight="1" android:background="#aaaaaa">
</LinearLayout>
</LinearLayout>
And you have to add to your manifest internet permission
uses-permission android:name="android.permission.INTERNET" />

how to switch between front and back camera when using MediaRecorder android

if anyone has any idea that how to switch between front and back camera when using MediaRecorder . I defing a button for this function, but have no idea how to define the onclickListener.
the total activity is the following:
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Test_cameraActivity extends Activity implements Callback {
// Camera variables to fiddle with video preview.
// private Camera cam;
// Viewholders etc
private SurfaceHolder recordViewHolder;
private SurfaceView recordSurface;
private int width, height;
// Button
private Button recordBut;
private Button switchBut;
private Button libraryBut;
private final static String DIRECTORY = "/hdrecorder"; // Directory where
// the film is
// stored
private final static String recordFileName = "/hdtestfile.mp4";
private final static String saveFileName = "/hdsavefile.mp4";
private MyMediaRecorder recorder = null;
private final static String LOG_TAG = "HD Recorder";
private String filePath;
// Activity overrides
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// *******************************************
// fullscreen mode
// *******************************************
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// *******************************************
setContentView(R.layout.main);
File dir = new File(Environment.getExternalStorageDirectory()
+ DIRECTORY);
if (!dir.exists()) {
if (dir.mkdir()) {
Log.v(LOG_TAG, "Created directory");
} else {
Log.v(LOG_TAG, "Failed to create Directory");
}
}
File videoFile = new File(Environment.getExternalStorageDirectory()
+ DIRECTORY + recordFileName);
if (!videoFile.exists()) {
videoFile.delete(); // Reset recording
}
filePath = videoFile.getAbsolutePath();
Log.v(LOG_TAG, "PATH:" + filePath);
Log.v(LOG_TAG, "PATH:" + filePath);
recordSurface = (SurfaceView) findViewById(R.id.videoSurface);
recordBut = (Button) findViewById(R.id.RecordBut);
recordBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (recorder.getState() != MyMediaRecorder.RECORDING) {
startRecord();
} else {
stopRecord();
recorder.release();
moveRecordFileToSave();
if (recorder == null) {
Log.v(LOG_TAG, "Recorder is null");
}
Log.v(LOG_TAG, "Value of recorder:" + recorder);
createRecorder();
initiateRecorder(recordViewHolder, width, height);
}
}
});
switchBut = (Button) findViewById(R.id.SwitchBut);
switchBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
libraryBut = (Button) findViewById(R.id.LibraryBut);
libraryBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Test_cameraActivity.this,
FileExplorer.class);
Test_cameraActivity.this.startActivity(intent);
}
});
recordViewHolder = recordSurface.getHolder();
recordViewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recordViewHolder.addCallback(this);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
createRecorder();
}
#Override
protected void onStart() {
super.onStart();
Log.v(LOG_TAG, "OnStart");
if (recorder != null) {
if (recorder.getState() == MyMediaRecorder.RELEASED) {
createRecorder();
}
}
Log.v(LOG_TAG, "SurfaceView create initiated. OnStart Done");
}
#Override
protected void onStop() {
super.onStop();
Log.v(LOG_TAG, "onStop received");
forceStopRecorder();
}
// General Helpers.
private void createRecorder() {
recorder = new MyMediaRecorder();
}
private void startRecord() {
if (recorder.getState() != MyMediaRecorder.PREPARED) {
Log.e(LOG_TAG, "Not recordable yet");
return;
}
recorder.start();
Log.v(LOG_TAG, "Recording started");
recordBut.setText("Stop Record");
}
private void stopRecord() {
Log.v(LOG_TAG, "Stop of recorder");
if (recorder.getState() == MyMediaRecorder.RECORDING) {
recorder.stop();
}
recorder.reset();
recordBut.setText("Record");
}
private void initiateRecorder(SurfaceHolder holder, int width, int height) {
Log.v(LOG_TAG, "H: " + height + " W:" + width);
if (recorder.getState() != MyMediaRecorder.INITIAL) {
Log.v(LOG_TAG, "Dude - not existing MediaRecorder - quitting");
return;
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(this.filePath);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setVideoSize(width, height);
recorder.setVideoFrameRate(24);
recorder.setPreviewDisplay(holder.getSurface());
Log.d(LOG_TAG, "Preview restarted");
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// isPrepared = true;
}
private void forceStopRecorder() {
Log.v(LOG_TAG, "Force release of recorder");
if (recorder.getState() != MyMediaRecorder.RELEASED) {
stopRecord();
recorder.release();
}
}
private void moveRecordFileToSave() {
File source = new File(filePath);
File dest = new File(Environment.getExternalStorageDirectory()
+ DIRECTORY + saveFileName);
if (dest.exists()) {
Log.v(LOG_TAG, "Delete old save file");
dest.delete();
}
source.renameTo(dest);
}
// ***** Implementing Callback ********/
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
recordViewHolder = holder;
this.width = width;
this.height = height;
if (recorder.getState() == MyMediaRecorder.RECORDING) {
stopRecord();
}
if (recorder.getState() == MyMediaRecorder.PREPARED) {
recorder.reset();
}
initiateRecorder(holder, width, height);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.v(LOG_TAG, "Surface is created: Path to use" + filePath);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.v(LOG_TAG, "Surface is Destroyed");
forceStopRecorder();
}
}
I have something that might also help, in order to jump to the other camera, follow this method:
public void flipit() {
//myCamera is the Camera object
if (Camera.getNumberOfCameras()>=2) {
myCamera.stopPreview();
myCamera.release();
//"which" is just an integer flag
switch (which) {
case 0:
myCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
which = 1;
break;
case 1:
myCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
which = 0;
break;
}
try {
myCamera.setPreviewDisplay(mHolder);
//"this" is a SurfaceView which implements SurfaceHolder.Callback,
//as found in the code examples
myCamera.setPreviewCallback(this);
myCamera.startPreview();
} catch (IOException exception) {
myCamera.release();
myCamera = null;
}
}
}
Now... for the magic trick, don't call this method from the main thread. Instead this method has to be kicked off from a separate thread, my code does this:
//btn is a Button that the user clicks on
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//onClick is invoked from main thread
//kick-off a different Thread to handle this call
Thread t = new Thread() {
public void run() {
//myViewer is the SurfaceView object which uses
//the camera
myViewer.flipit();
}
};
t.start();
}
});
I've tested this on Android 4.1.1 so I think it might work for you. (or until Google decides to break the way the camera opening/closing/releasing/unlocking/reconnecting/surfaceholder/onPause/onResume/etc..? works)
First, check if your device has more than one camera:
Camera.getNumberOfCameras();
Then, assign a camId value:
camId = Camera.CameraInfo.CAMERA_FACING_BACK;
or
camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
and then creates a new Camera object to access a particular hardware camera (camId).
mCamera = Camera.open(camId);
Hope this help!

error due to R.java

I'm new to Android programming and as a part of learning i tried to run this open source project(below) which ends up in an error at the import com.example.android.apis.R;. Also where and all there is R. As far as i know R.java is automatically generated and we don't need to create it or edit it. What is the reason for this error. Can anyone please explain this. I used Eclipse to run this project.
package com.example.android.apis.media;
import com.example.android.apis.R;
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.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 MediaPlayerDemo_Video extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, 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 Bundle extras;
private static final String MEDIA = "media";
private static final int LOCAL_AUDIO = 1;
private static final int STREAM_AUDIO = 2;
private static final int RESOURCES_AUDIO = 3;
private static final int LOCAL_VIDEO = 4;
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
switch (Media) {
case LOCAL_VIDEO:
/*
* TODO: Set the path variable to a local media file path.
*/
path = "";
if (path == "") {
// Tell the user to provide a media file URL.
Toast
.makeText(
MediaPlayerDemo_Video.this,
"Please edit
MediaPlayerDemo_Video Activity, "
+ "and set the path
variable to your media file path."
+ " Your media file
must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
break;
case STREAM_VIDEO:
/*
* TODO: Set path variable to progressive streamable mp4 or
* 3gpp format URL. Http protocol should be used.
* Mediaplayer can only play "progressive streamable
* contents" which basically means: 1. the movie atom has to
* precede all the media data atoms. 2. The clip has to be
* reasonably interleaved.
*
*/
path = "";
if (path == "") {
// Tell the user to provide a media file URL.
Toast
.makeText(
MediaPlayerDemo_Video.this,
"Please edit
MediaPlayerDemo_Video Activity,"
+ " and set the path
variable to your media file URL.",
Toast.LENGTH_LONG).show();
}
break;
}
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
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 onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height("
+ height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
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");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
}
#Override
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();
}
}
This is the code i tried to run.
I fixed this problem by changing the project build target from Android 1.6 to Android 4.2 in Project Property/*Android*.
Some new syntax in layout xml files are not supported in old version but these error information is not display in the source code but in the output window.
This can have several causes.
Make sure that you don't have any XML errors in all your files. The R. file will not be built when you have XML errors. After you fixed the errors the R. file should be built automatically. If not, try cleaning your project.
Also, make sure you do not have this line:
import android.R;
in your class.
That implies errors on the layout or Manifest file , which are XML .
I think the common mistakes can be the error of layout design , missing tags , and so on
please Fix them first and clean the project again

How to put media controller in streaming video?

I am using SurfaceView to play streaming video and Media Player for streaming video. Can any one tell me how can I place media controller in surfaceview?
Here's my code:
package com.menu.donationvideos;
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.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.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;
import android.widget.VideoView;
import com.menu.R;
public class VideoPlay extends Activity implements OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback
{
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
SurfaceHolder holder;
VideoInfo videoInfo;
String pos,videoURL;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private String path;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.video_play);
Bundle bundle=new Bundle();
bundle=this.getIntent().getExtras();
pos=bundle.getString("position");
videoInfo=VideoList.m_video.get(Integer.parseInt(pos));
videoURL=videoInfo.getVideoFile();
try
{
mPreview = (SurfaceView)findViewById(R.id.mySurfaceView);
holder=mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void playVideo()
{
doCleanUp();
try
{
path = videoURL;
if (path == "")
{
Toast.makeText(VideoPlay.this,"URL Not found", Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent)
{
Log.d(TAG,"Buffering:"+percent);
}
public void onCompletion(MediaPlayer arg0)
{
Log.d(TAG, "onCompletion called");
finish();
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height)
{
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0)
{
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown)
{
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer)
{
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown)
{
startVideoPlayback();
}
}
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");
}
public void surfaceCreated(SurfaceHolder holder)
{
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#Override
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();
}
}
do {
numread = stream.read(buf);
if (numread <= 0)
break;
totalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
Log.e(getClass().getName(),"Buffered byte: " +totalBytesRead+"");
if(totalBytesRead>=100000){
if(mediaPlayer!=null){
int dura = mediaPlayer.getDuration();
if(mediaPlayer.getDuration()>=90000){
isInterrupted =false;
stream.close();
out.close();
out.flush();
break;
}
}
}
This is my code but I realized that media player doesnt start until streaming in progress.
I would suggest you take a look at the source code of VideoView, which combines everything at first place (or use VideoView instead of MediaPlayer itself)
hey nirav this code try it for media streaming
package com.pocketjourney.media;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
/**
* MediaPlayer does not yet support streaming from external URLs so this class provides a pseudo-streaming function
* by downloading the content incrementally & playing as soon as we get enough audio in our temporary storage.
*/
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96*10/8;//assume 96kbps*10secs/8bits per byte
private TextView textStreamed;
private ImageButton playButton;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context,TextView textStreamed, ImageButton playButton, Button streamButton,ProgressBar progressBar)
{
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
}
/**
* Progressivly download the media to a temporary location and update the MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl, long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(), "Unable to initialize the MediaPlayer for fileUrl=" + mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
/**
* Download the url stream to a temporary location and then call the setDataSource
* for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException {
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);
}
downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia.dat");
// Just in case a prior deletion failed because our code crashed or something, we also delete any previously
// downloaded file to ensure we start fresh. If you use this code, always delete
// no longer used downloads else you'll quickly fill up your hard disk memory. Of course, you can also
// store any previously downloaded file in a separate data cache for instant replay if you wanted as well.
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
//mediaPlayer.release();
}
return false;
} else {
return true;
}
}
/**
* Test whether we need to transfer buffered data to the MediaPlayer.
* Interacting with MediaPlayer on non-main UI thread can causes crashes to so perform this using a Handler.
*/
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum buffered data
if ( totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(), "Error copying buffered conent.", e);
}
}
} else if ( mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000 ){
// NOTE: The media player has stopped at the end so transfer any existing buffered data
// We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// We double buffer the data to avoid potential read/write errors that could happen if the
// download thread attempted to write at the same time the MediaPlayer was trying to read.
// For example, we can't guarantee that the MediaPlayer won't open a file for playing and leave it locked while
// the media is playing. This would permanently deadlock the file download. To avoid such a deadloack,
// we move the currently loaded data to a temporary buffer file that we start playing while the remaining
// data downloads.
moveFile(downloadingMediaFile,bufferedFile);
Log.e(getClass().getName(),"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),"Buffered File length: " + bufferedFile.length()+"");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile)
throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
return false;
}
});
// It appears that for security/permission reasons, it is better to pass a FileDescriptor rather than a direct path to the File.
// Also I have seen errors such as "PVMFErrNotSupported" and "Prepare failed.: status=0x1" if a file path String is passed to
// setDataSource(). So unless otherwise noted, we use a FileDescriptor here.
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
/**
* Transfer buffered data to the MediaPlayer.
* NOTE: Interacting with a MediaPlayer on a non-main UI thread can cause thread-lock and crashes so
* this method should always be called using a Handler.
*/
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File. Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on exit. If it's already deleted, then this won't mean anything. If you want to
// keep and track fully downloaded files for later use, write caching code and please send me a copy.
bufferedFile.deleteOnExit();
moveFile(downloadingMediaFile,bufferedFile);
// Pause the current player now as we are about to create and start a new one. So far (Android v1.5),
// this always happens so quickly that the user never realized we've stopped the player and started a new one
mediaPlayer.pause();
// Create a new MediaPlayer rather than try to re-prepare the prior one.
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
// Restart if at end of prior buffered content or mediaPlayer was previously playing.
// NOTE: We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
boolean atEndOfFile = mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile){
mediaPlayer.start();
}
// Lastly delete the previously playing buffered File as it's no longer needed.
oldBufferedFile.delete();
}catch (Exception e) {
Log.e(getClass().getName(), "Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
textStreamed.setText((totalKbRead + " Kb read"));
float loadProgress = ((float)totalKbRead/(float)mediaLengthInKb);
progressBar.setSecondaryProgress((int)(loadProgress*100));
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float)mediaPlayer.getCurrentPosition()/1000)/mediaLengthInSeconds);
progressBar.setProgress((int)(progress*100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
/**
* Move the file in oldLocation to newLocation.
*/
public void moveFile(File oldLocation, File newLocation)
throws IOException {
if ( oldLocation.exists( )) {
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(getClass().getName(),"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() );
}
}
}

Categories

Resources