I'm building an application to live stream video from the raspberry pi to my android device. I have three functional ways of playing this stream:
rtsp://media.smart-streaming.com/mytest/mp4:sample_phone_150k.mp4
Media Player + SurfaceView
VideoView
Intent.ACTION_VIEW
The problem is the application plays the above^ stream but doesn't play mine (rtsp://192.168.1.143:8554/vid.mp4) ... but VLC does.
I have tried streaming with VLC and with LIVE555 in multiple video formats and I've also tried playing a video that was recorded on the phone.
Here is my code:
//Stream methods 0 = MediaPlayer & SurfaceView, 1 = VideoView, 2 = Native Video Player
final int STREAM_USING = 0;
//MediaPlayer on surfaceView
String streamPath = "rtsp://192.168.1.143:8554/vid.mp4";//"rtsp://media.smart-streaming.com/mytest/mp4:sample_phone_150k.mp4";//"rtsp://192.168.1.143:8554/vid.mp4";//;"rtp://239.255.0.1:5004/";
Uri streamUri;
private MediaPlayer mediaPlayer;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
//VideoView
VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//MediaPlayer
switch (STREAM_USING) {
case 0: {
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFixedSize(800, 480);
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
//mediaPlayer.stop();
play();
}
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Toast.makeText(getApplicationContext(), "BUFF : " + percent, Toast.LENGTH_SHORT).show();
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
});
//Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//i.setType("video/*");
//startActivityForResult(i, 1234);
streamUri = Uri.parse(streamPath);
play();
break;
}
case 1: {
videoView = (VideoView) findViewById(R.id.videoView);
videoView.setVideoURI(Uri.parse(streamPath));
MediaController mediaController = new MediaController(this);
//mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.requestFocus();
try {
videoView.start();
}
catch (SecurityException se) {
Log.e("SE", se.getMessage());
se.printStackTrace();
}
break;
}
case 2: {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(streamPath));
startActivity(intent);
break;
}
default: {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(streamPath));
startActivity(intent);
}
}
}
private void play() {
try {
//final FileInputStream fis = new FileInputStream(streamPath);
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(MainActivity.this, streamUri);
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
//mediaPlayer.reset();
mediaPlayer.start();
}
});
} catch (SecurityException se) {
Log.e("SE", se.getMessage());
se.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
Any help is appreciated, I've been trying for a week to get this to work with no success :(
You already added two ways just i want to add bit modification. I have done streaming ralalted task.I have used rtsp with wowza.Few ways i'll let you know
try it once and let me know if you got issue.If your streaming in vlc working fine then something problem with app side. If these methods are not working then try with different phone. It also help you.
1. Try with videoview
vvVideoPlay = (VideoView) findViewById(R.id.vvVideoPlay);
MediaController mediaController = new MediaController(this);
String videoUrl = "rtsp://192.168.1.143:8554/vid.mp4";
mediaController.setAnchorView(vvVideoPlay);
Uri uri = Uri.parse(videoUrl);
vvVideoPlay.setVideoURI(uri);
vvVideoPlay.setMediaController(mediaController);
vvVideoPlay.requestFocus();
vvVideoPlay.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
pdialog.dismiss();
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mp.start();
}
});
}
});
2. Try with direct your phone player
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("rtsp://192.168.1.143:8554/vid.mp4")));
3. Third way try to with this library with custom player in your app.
Step1. Add it to your gradle
compile "fm.jiecao:jiecaovideoplayer:4.7.0"
Step2. Add it as your video play in xml layout.
<fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
android:id="#+id/videoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Step 3. Check from here how to use this library in your class,
public class PlayVideoActivity extends BaseActivity {
#BindView(R.id.videoPlayer)
JCVideoPlayerStandard mVideoPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
restoreFromIntent(getIntent());
}
#Override
public int getLayout() {
return R.layout.activity_play_video;
}
// get video path from intent and play the video here
private void restoreFromIntent(Intent intent) {
mVideoPlayer.setUp("rtsp://192.168.1.143:8554/vid.mp4"
, JCVideoPlayerStandard.SCREEN_LAYOUT_LIST, "");
}
#Override
public void onBackPressed() {
if (JCVideoPlayer.backPress()) {
return;
}
super.onBackPressed();
}
#Override
protected void onPause() {
super.onPause();
JCVideoPlayer.releaseAllVideos();
}
}
Hope this will help you to fix your problem.Thanks
Related
I'm playing video from web server, the video is playing on videoview nicely, but some samsung mobile playing the video on 90 degree rotation. But the same video playing without ration on others devices.
public void playVideo(String videoPath) {
try {
vidFull.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_INFO_BUFFERING_START:
progressBar.setVisibility(View.VISIBLE);
break;
case MediaPlayer.MEDIA_INFO_BUFFERING_END:
progressBar.setVisibility(View.GONE);
break;
}
return false;
}
});
}
});
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(vidFull);
vidFull.setMediaController(mediaController);
vidFull.setVideoPath(videoPath);
vidFull.requestFocus();
vidFull.start();
videoArrayLength = videoArrayLength -1;
vidpointer = 1;
//Goutam 17.03.2016
vidFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
logCollection.setLogERed(""+videoArrayLength);
try {
if (videoArrayLength > 0){
MediaController mediaController = new MediaController(FullPost.this);
mediaController.setAnchorView(vidFull);
vidFull.setMediaController(mediaController);
//vidFull.setVideoPath("http://www.sample-videos.com/video/mp4/480/big_buck_bunny_480p_1mb.mp4");
logCollection.setLogERed(basevideourl+videoArray.optJSONObject(vidpointer).getString("vdLink"));
vidFull.setVideoPath(basevideourl + videoArray.optJSONObject(vidpointer).getString("vdLink"));
vidFull.requestFocus();
vidFull.start();
videoArrayLength = videoArrayLength - 1;
vidpointer = vidpointer + 1;
}else {
logCollection.showToastLong("No more video to play.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, "Error connecting", Toast.LENGTH_SHORT).show();
}
}
Please help, thanks in advance.
I think you telling about orientation change. You can handle this by setting screenOrientation to activity in AndroidManifest.
<activity android:name=".Main2Activity"
android:screenOrientation="portrait">
</activity>
I need to play multiple (correct :2 ) mp3 files loaded from my assets when a button is clicked. If the button is again clicked 2 new songs should be played and the old ones should be stopped immidiatelly.The process is on going...
At the moment I have achieved this by stupidly creating 2 mediaPlayer instances in 2 separate methods that basically have the same body .
The caller is an onTouch method and ,within it, first I call method 1 ,then sleep for 2 secs ,then call method 2. I m sure there must be a way for this to be more elegant code? For example I have implemented some listeners that are just sitting there (Actually tried to make this work but totally screwed up with Illegal States all over the place ). Ideally I would like to use 1 MediaPlayer and one method for playing every sound in my app.
int carouzelIndex = 0
#Override
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
...
if (e.getAction() == MotionEvent.ACTION_UP) {
carouzelIndex++;
Assets.playMusic1("music1.ogg",false);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assets.playMusic2("music2.ogg",false);
}
}
}
}
Now my player methods 1 and 2 (playMusic1() and playMusic2() )are the same. Both are instansiating different MediaPlayers and for the shake of simplicity I write just one copy in the post
Public class Assets
MediaPlayer mediaPlayer;
public static void playMusic(String filename, boolean looping) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer.setOnInfoListener(new OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
For immediate playback you need two MediaPlayer set up and chained together via OnCompletionListener
You can do it like this:
Note that I also deleted some unnecessary overrides, you might add them again if you need them.
Public class Assets{
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
boolean mediaplayer2prepared = false;
boolean mediaplayer1finished = false;
public static void playMusic(String filename, boolean looping, String filename2, boolean looping2) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 == null) {
mediaPlayer2 = new MediaPlayer();
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
mediaplayer2prepared = false;
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
mediaplayer1finished = false;
}
if (mediaPlayer2 != null) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = new MediaPlayer();
mediaplayer2prepared = false;
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
if(mediaplayer2prepared)
mediaplayer2.start();
mediaplayer1finished = true;
}
});
mediaPlayer.prepareAsync();
afd2 = GameMainActivity.assets.openFd(filename2);
mediaPlayer2.setDataSource(afd2.getFileDescriptor(),
afd2.getStartOffset(), afd2.getLength());
afd2.close();
mediaPlayer2.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
mediaplayer2prepared = true;
if(mediaplayer1finished && !mp.isPlaying()){
mp.start();
}
}
});
mediaPlayer2.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To start both mediaplayers in succession simply do Assets.playMusic("music1.ogg",false, "music2.ogg",false);
You can try something like this. Use a single mediaplayer in a single thread. It is an asynchronous operation so it will go on also if the thread is paused. I think it would work.
private Thread t = null;
private MediaPlayer mediaPlayer;
...
Button b=findViewById(R.id.yourButtonId);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//if button had previously clicked stop audio reproduction
if(mediaPlayer.isPlaying()) mediaPlayer.stop();
if(t.isAlive()) t.stop();
String[] files;
//Here you have to set your filenames in the array
...
...
//Now play that audio
playMusic(files, false);
}
});
...
protected static void playMusic(String[] files, boolean looping){
AssetFileDescriptor afd = null;
Log.e("Assets", "Playing music");
t=new Thread(){
#Override
public void run(){
//Initialize mediaPlayer
for(String filename:files){
mediaPlayer=new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
afd = GameMainAcivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
if(!mp.isPlaying()) mp.start();
}
});
//while audio is playing wait in this position
while(mediaPlayer.isPlaying()){
this.wait(100);
}
//now loop can restart with the other filename that has
//to be reproduced
}
}
};
t.start();
}
Here is my code snippet where I want to play a video coming from server
private void PlayVideo() {
try {
getWindow().setFormat(PixelFormat.TRANSLUCENT);
MediaController mediaController = new MediaController(VideoActivity.this);
mediaController.setAnchorView(videoView);
Uri video = Uri.parse(videoPath);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.requestFocus();
videoPlayer.removeAllViews();
videoPlayer.setVisibility(View.GONE);
videoView.setVisibility(View.VISIBLE);
videoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
dismissProgressDialog();
videoView.bringToFront();
videoView.setFocusable(true);
videoView.start();
contentStarted = true;
}
});
videoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
contentStarted = false;
}
});
videoView.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
dismissProgressDialog();
Intent in = new Intent();
setResult(1, in);
finish();
return false;
}
});
} catch (Exception e) {
dismissProgressDialog();
finish();
}
}
The ProgressDialog is dismissed only in videoView.setOnPreparedListener and videoView.setOnErrorListener. But the ProgressDialog is not getting dismissed and video is not getting played. I tried to put Logs and see, Logs are printed upto just before videoView.setOnPreparedListener and after that no Logs are displayed. Listeners are not getting registered I guess.
Any help is appreciated.
Thanks in advance.
EDIT:
'M trying to stream a live video, if video is availbale it should go to videoView.setOnPreparedListener and should play the video. If Live is not available(i.e, Video will be live after some time) then it should go to videoView.setOnErrorListener and return to previous Activity with result "1"
and
Video is streamed over RTSP
After a lot of research and with the help of Preethi Rao I got to know that the fault was in the URL.
The URL might have the video (if it is time for Live Video) and might not have video (if Live Video will be streaming after some time). If I'm trying to stream video when Live Video is not available then the Listeners are not getting fired. If Live Video is availbale, Listeners are getting fired. So, videoView.setOnPreparedListener and videoView.setOnErrorListener are not getting attached.
I wrote a handler to run for 60 seconds and if no Listeners are attached I'm just returning to previous Activity.
Here's the code:
private void PlayVideo() {
try {
isListenerAttached = false;
getWindow().setFormat(PixelFormat.TRANSLUCENT);
MediaController mediaController = new MediaController(VideoActivity.this);
mediaController.setAnchorView(videoView);
Uri video = Uri.parse(videoPath);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.requestFocus();
videoPlayer.removeAllViews();
videoPlayer.setVisibility(View.GONE);
videoView.setVisibility(View.VISIBLE);
// Using this Handler to revert to previous Activity when the Video View is not attached to Listeners
// As the Buffering Video dialog doesn't get dismissed if Video View is not attached to Listeners
runOnUiThread(new Runnable() {
#Override
public void run() {
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
if(!isListenerAttached){
dismissProgressDialog();
Intent in = new Intent();
setResult(1, in);
finish();
}
}
}, WAIT_TIME);
}
});
videoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
isListenerAttached = true;
dismissProgressDialog();
videoView.bringToFront();
videoView.setFocusable(true);
videoView.start();
contentStarted = true;
}
});
videoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
contentStarted = false;
}
});
videoView.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
isListenerAttached = true;
dismissProgressDialog();
Intent in = new Intent();
setResult(1, in);
finish();
return false;
}
});
} catch (Exception e) {
dismissProgressDialog();
finish();
}
}
I have a splahs screen in my application and i am playing a video on that activity. But in some Android versions ( i mean old ) the video doesnt play. i dont know what to do..
here is some of my code
public void PlayVideo(){
try{
videoPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.afad_splash_ip4));
videoPlayer.prepare();
}
catch (Exception e){
}
try {
AssetFileDescriptor descriptor = getAssets().openFd("splash.mp4");
videoPlayer.reset();
videoPlayer.setDataSource(descriptor.getFileDescriptor());
videoPlayer.prepare();
}
catch (Exception ex)
{
try
{
Log.v("video ", "catch");
videoPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
videoPlayer.setVolume(0f, 0f);
videoPlayer.start();
videoPlayer.setLooping(false);
videoPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Intent i = new Intent(VideoSplash.this,ListActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
overridePendingTransition(R.anim.slide_in_top,R.anim.slide_out_bottom);
finish();
}
});
}
catch (Exception e)
{ //TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
Log.v("resim", "catch");
//Thats where i want to put a pic as a backgroun to my SurfaceView. and make it wait 10 secs
// videoSurface.setBackgroundDrawable(getResources().getDrawable(R.drawable.son_frame));
}
//TODO
//Burada Video yerine resim koymalısın
//Kimi cihazlarda video oynamayabilir
}
}
Try this code will help you
public class VideoPlayerActivity extends Activity implements OnErrorListener,
OnPreparedListener {
LoadAsyncTask video_async_task;
private VideoView mVideoView
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.video);
mVideoView = (VideoView) findViewById(R.id.mysurfaceview);
mVideoView.setMediaController(myctrl);
mVideoView.requestFocus();
video_async_task = new LoadAsyncTask();
video_async_task.execute();
}
private class LoadAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
mVideoView.setVideoURI(Uri.parse(path));
}
}
i am new to android, currently doing dynamic multimedia application. For accessing videos, included tappable SurfaceView. whenever playing videos from localhost server, only sound's can visible, there is no visual. i am not sure why this will happen, can anyone guide me how to visualize the video.
if (player == null) {
player = new MediaPlayer();
player.setScreenOnWhilePlaying(true);
} else {
player.stop();
player.reset();
}
player.setDataSource(file);
player.setDisplay(holder);
player.prepareAsync();
//player.setOnBufferingUpdateListener(this);
player.setOnCompletionListener(this);
player.setOnPreparedListener(this);
player.setOnVideoSizeChangedListener(this);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Here setDataSoruce (file) is used to get localhost url from existing class using intent.
Check out my Surface View - Playing video tutorial
public class VideoAssetActivity extends Activity implements
TextureView.SurfaceTextureListener {
// Log tag.
private static final String TAG = VideoAssetActivity.class.getName();
// Asset video file name.
private static final String FILE_NAME = "big_buck_bunny.mp4";
// MediaPlayer instance to control playback of video file.
private MediaPlayer mMediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.texture_video_simple);
initView();
}
private void initView() {
TextureView textureView = (TextureView) findViewById(R.id.textureView);
textureView.setSurfaceTextureListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i2) {
Surface surface = new Surface(surfaceTexture);
try {
AssetFileDescriptor afd = getAssets().openFd(FILE_NAME);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
// Play video when the media source is ready for playback.
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e) {
Log.d(TAG, e.getMessage());
} catch (SecurityException e) {
Log.d(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i2) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
}
}