Native thread exited without detaching - android

I want to play stream video using this code and vitamio lib
when I run this code it make exception
this is code
private void playVideo(String path) {
doCleanUp();
try {
if (path == "") {
// Tell the user to provide a media file URL.
Toast.makeText(
this,
"Please edit Your Path,"
+ " and set the path variable to your media file URL.",
Toast.LENGTH_LONG).show();
return;
} else {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
} catch (Exception e) {
Log.i(TAG, "PlayVideoException");
Log.e(TAG, "error: " + e.getMessage(), e);
// Toast.makeText(this, "sorry", Toast.LENGTH_LONG).show();
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
// Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public long getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public long getDuration() {
return mMediaPlayer.getDuration();
}
public boolean onError(MediaPlayer mp, int whatError, int extra) {
if (whatError == MediaPlayer.MEDIA_ERROR_IO) {
Log.v(TAG, "Media Error, Server Died " + extra);
} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
Log.v(TAG, "Media Error, Error Unknown " + extra);
}
isVideoError = true;
return false;
}
public void onCompletion(MediaPlayer arg0) {
onComplete = true;
Log.d(TAG, "onCompletion called");
Log.i(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");
try {
doTimerTaskforVideo();
} catch (Exception e) {
Log.d(TAG, "surfaceCreated created Exception");
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
TRS.RssTimer.cancel();
VideoTimer.cancel();
XMLTimer.cancel();
surfaceDestroyed(holder);
releaseMediaPlayer();
mMediaPlayer = null;
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();
}
and exception is:
05-17 20:17:55.715: E/dalvikvm(21042): threadid=17: native thread exited without detaching
05-17 20:17:55.715: E/dalvikvm(21042): VM aborting
05-17 20:17:55.715: A/libc(21042): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 21543 (helnix.signage)
How I can determine what thread that make that exception and how to prevent this exception
In same project now show this exception
05-18 16:58:44.080: E/Vitamio[4.2.1][Player](4327): stop called in state 4
thanks in advance

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();
}
}

Android Vitamio 4.2 update 5.0 crash

I updated Vitamio 4.2.2 to 5.0.0 as Google requested because of security issues in developer console. But with the same codes. Only changed Vitamio.isInitialized(getApplicationContext()); There is not error. Application was installed. But video not playing. How can i do for this?
public class MainActivity extends Activity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static String TAG = MainActivity.class.getSimpleName();
private static String ShowTV = "http://mn-i.mncdn.com/showtv_ios/smil:showtv.smil/playlist.m3u8";";
private TextView tvLoader;
private int mVideoWidth;
private int mVideoHeight;
public MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vitamio.isInitialized(getApplicationContext());
if (Build.VERSION.SDK_INT < 16)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
else
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
tvLoader = (TextView) findViewById(R.id.tvLoader);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setFormat(PixelFormat.RGBA_8888);
}
public void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(ShowTv);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
setVolumeControlStream(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;
tvLoader.setVisibility(View.GONE);
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();
}
public void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
tvLoader = (TextView) findViewById(R.id.tvLoader);
tvLoader.setVisibility(View.VISIBLE);
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}

How to resume MediaPlayer in Android after pressing the home button and reopen the app

I tried a lot of methods, I made a lot of changes on my code, I read Android MediaPlayer document, I tried StackOverflow examples but none of them could solve my problem.
My problem: When I press the home button of emulator or phone then reopen the app it is starting from the beginning.
Hope you can help me. Thanks in advance.
Here is my code :
public class Mediaplayer extends Activity implements OnCompletionListener,
OnErrorListener, OnInfoListener, OnPreparedListener,
OnSeekCompleteListener, OnVideoSizeChangedListener,
SurfaceHolder.Callback, MediaController.MediaPlayerControl {
Display currentDisplay;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
MediaController controller;
int videoWidth = 0;
int videoHeight = 0;
boolean readyToPlay = false;
public final static String LOGTAG = "CUSTOM_VIDEO_PLAYER";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video);
surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
mediaPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
String filePath = "http://cdn.example.com/wp-content/uploads/Almost.Human-S01E10.mp4";
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IllegalStateException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IOException e) {
Log.v(LOGTAG, e.getMessage());
finish();
}
controller = new MediaController(this);
currentDisplay = getWindowManager().getDefaultDisplay();
}
public void surfaceCreated(SurfaceHolder holder) {
// Log.v(LOGTAG, "surfaceCreated Called");
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// Log.v(LOGTAG, e.getMessage());
finish();
} catch (IOException e) {
// Log.v(LOGTAG, e.getMessage());
finish();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.v(LOGTAG, "surfaceChanged Called");
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed Called");
}
public void onCompletion(MediaPlayer mp) {
Log.v(LOGTAG, "onCompletion Called");
finish();
}
public boolean onError(MediaPlayer mp, int whatError, int extra) {
Log.v(LOGTAG, "onError Called");
if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
Log.v(LOGTAG, "Media Error, Server Died " + extra);
} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
}
return false;
}
public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
/*
* Android Version 2.0 and Higher } else if (whatInfo ==
* MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
* Log.v(LOGTAG,"MediaInfo, Media Info Metadata Update " + extra);
*/
}
return false;
}
public void onPrepared(MediaPlayer mp) {
Log.v(LOGTAG, "onPrepared Called");
videoWidth = mp.getVideoWidth();
videoHeight = mp.getVideoHeight();
if (videoWidth > currentDisplay.getWidth()
|| videoHeight > currentDisplay.getHeight()) {
float heightRatio = (float) videoHeight
/ (float) currentDisplay.getHeight();
float widthRatio = (float) videoWidth
/ (float) currentDisplay.getWidth();
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) heightRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) heightRatio);
} else {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) widthRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) widthRatio);
}
}
}
surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
videoHeight));
mp.start();
controller.setMediaPlayer(this);
controller.setAnchorView(this.findViewById(R.id.MainView));
controller.setEnabled(true);
controller.show();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
return;
}
}
public void onSeekComplete(MediaPlayer mp) {
Log.v(LOGTAG, "onSeekComplete Called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(LOGTAG, "onVideoSizeChanged Called");
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
public void start() {
mediaPlayer.start();
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
controller.show();
return false;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
I understand you have accepted an answer but I'll explain what the problem was based on your comments on your question and the comments from you and Nana on Nana's answer.
A SurfaceView is destroyed when it is no longer visible and recreated when it becomes visible again.
You are calling mp.pause() in your Activity onPause() method.
When you go to the 'recent' apps list and attempt to restart the app, the SurfaceView is recreated.
In surfaceCreated method you are calling mp.prepare() but at this point mp is in a paused state and calling prepare() on a paused Mediaplayer will throw an IllegalStateException.
You have a try / catch block which catches IllegalStateException and calls finish() - this is why the first attempt to restart the app from the 'recent' list causes the the Activity to be destroyed.
As a result of the above sequence of events you need a second attempt to re-open the app from the 'recent' list but as the Activity has been destroyed it will go through a full creation (with onCreate(..) being called. This is why it starts from the beginning.
The answer from Nana is a workaround but it will still mean having to use two attempts to restart your Activity from the 'recent' list.
Unfortunately the MediaPlayer class is lacking in methods for checking the 'state' with isPlaying being the only useful method for any state. It's a shame the class devs didn't think to add a getState() method (or similar) to allow checking for whether it's started, playing, stopped, paused etc.
One way of preventing the IllegalStateException would be to have a boolean called isPaused (for example) then modify your Activity onPause() as follows...
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
isPaused = true;
}
...and in surfaceCreated(...)...
try {
if (isPaused) {
mpStart();
isPaused = false;
}
else
mediaPlayer.prepare();
}
// catch blocks here
The activity is being restarted thereby triggering surfaceCreated() and mediaPlayer.prepare(), which in turns calls onPrepared and mp.start() to restart the track. You have no mechanism to resume playing. Do this - Get the last position of the track when paused(HOME button is pressed), then when the activity is "recreated" resume playing the track by seeking to that last position. Modify your onPause() and onPrepared() as follows:
int length = 0;
//save last position when activity is paused
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
length = mediaPlayer.getCurrentPosition();
} else {
return;
}
}
public void onPrepared(MediaPlayer mp) {
........
.........
.........
mp.start();
//seek to saved position.
mp.seekTo(length);
}

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" />

Asynchronous Video Streaming Android

I have been working on video playback of progressive videos from my android application. I am able to stream videos from internet.
But the video starts after buffering the whole data.
Here is the code I am using-
private static final String MOVIEURL = "movieUrl";
private static final String TAG = "VideoPlayerActivity";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
protected 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(String movieUrl) {
doCleanUp();
try {
path=movieUrl;
// 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);
return false;
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
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.getString(MOVIEURL));
}
#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 startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
This code is working fine, but not playing before the whole video gets buffered.
Is there anyway we can stream the video while buffering it in the background.
Thanks.
Instead of
mMediaPlayer.prepare();
Use :
mMediaPlayer.prepareAsync();

Categories

Resources