How to play a particular video from ExoPlayer playlist android? - android

I'm using ExoPlayer to play a list of videos as playlist:
MediaSource[] mediaSources = new MediaSource[mList.size()];
for (int i = 0; i < mList.size(); i++) {
mediaSources[i] = buildMediaSource(Uri.parse(mList.get(i));
}
MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
: new ConcatenatingMediaSource(mediaSources);
mExoPlayer.prepare(mediaSource);
Its working fine. But as per requirement I have to play a video in a particular position from the list when click. How can I achieve this?
Thanks!

You may want to use seekTo(windowIndex, positionMs).
player.prepare(mediaSource);
player.seek(3, C.TIME_UNSET);
player.setPlayWhenReady(true);

Here is a sample code that plays video in a particular position from the list when click.
//Pass the position of the item on the listview/playlist from previous activity /fragment.
Intent _intent = getIntent();
position = _intent.getIntExtra("postion_id", 0);
player = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector());
playerView.setPlayer(player);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory (this, Util.getUserAgent(this, "exo-demo"));
ConcatenatingMediaSource concatenatingMediaSource = new ConcatenatingMediaSource();
//Ensure to populate the allFiles array.
for (int i = 0; i < allFiles.size(); i++) {
File currentFile = new File(allFiles.get(i));
MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse("file://" + currentFile.getAbsolutePath()));
concatenatingMediaSource.addMediaSource(mediaSource);
}
player.prepare(concatenatingMediaSource);
//Play from the item selected on the playlist from previous activity/fragment
player.seekTo(position, C.TIME_UNSET);
player.setPlayWhenReady(true);
player.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
//THIS METHOD GETS CALLED FOR EVERY NEW SOURCE THAT IS PLAYED
int latestWindowIndex = player.getCurrentWindowIndex();
if (latestWindowIndex != position) {
// item selected in playlist has changed, handle here
position = latestWindowIndex;
// ...
}
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});

How to play a particular video from the playlist in ExoPlayer using JAVA android studio project
ExoPlayer player;
player = new ExoPlayer.Builder(this).build(); //this is the latest version as of now
player.addMediaItems(mediaItemArrayList); //playlist has been added
player.seekToDefaultPosition(position); //THIS IS WHAT YOU ARE LOOKING FOR
//player.setMediaItems(mediaItemArrayList,position,startingTime); //alternative way
player.prepare();
player.play();

Related

Play video on exo player, from my youtube live streaming

I want to broadcast my Youtube live streaming videos to my android mobile app, i.e. when i go live on Youtube that video i want to play in exo player.
This is my code of exoplayer to play live video url.
I have used the youtube extractor implementation 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
new YouTubeExtractor(this) {
#Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
if (ytFiles != null) {
String url = ytFiles.get(22).getUrl();
playVideo(url);
}
}
}.extract("https://www.youtube.com/watch?v=LCfuylCR5ZQ", true, true);
private void playVideo() {
//Creating default track selector
TrackSelection.Factory adaptiveTrackSelection = new AdaptiveTrackSelection.Factory(new DefaultBandwidthMeter());
player = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(ExoPlayerJavaActivity.this),
new DefaultTrackSelector(adaptiveTrackSelection),
new DefaultLoadControl());
playerView.setPlayer(player);
DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(ExoPlayerJavaActivity.this,
Util.getUserAgent(ExoPlayerJavaActivity.this, "Employee Management"), defaultBandwidthMeter);
Uri uri = Uri.parse("https://www.youtube.com/watch?v=LCfuylCR5ZQ");
Handler mainHandler = new Handler();
MediaSource mediaSource = new HlsMediaSource(uri,
dataSourceFactory, mainHandler, null);
player.prepare(mediaSource);
player.setPlayWhenReady(playWhenReady);
player.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case ExoPlayer.STATE_READY:
loading.setVisibility(View.GONE);
break;
case ExoPlayer.STATE_BUFFERING:
loading.setVisibility(View.VISIBLE);
break;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
player.seekTo(currentWindow, playbackPosition);
player.prepare(mediaSource, true, false);
}
Still i am getting this error. I just wanted to play my channels live video on exo player.
E/ExoPlayerImplInternal: Source error.
com.google.android.exoplayer2.source.UnrecognizedInputFormatException: Input does not start with the #EXTM3U header.
at com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistParser.parse(HlsPlaylistParser.java:149)
at com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistParser.parse(HlsPlaylistParser.java:48)
at com.google.android.exoplayer2.upstream.ParsingLoadable.load(ParsingLoadable.java:138)
at com.google.android.exoplayer2.upstream.Loader$LoadTask.run(Loader.java:320)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)

Can I play second media source if I get error on first in exoplayer?

I am Beginner android. Can anyone help me in brief about this problem. I am getting two links dynamically
url
alternate
I want to play second media(alternate) source if I get an error on the first one (url).
I am searching this for a week, a good answer will be appreciated. if you unable to solve please upvote it to get into more eyes.. Thanks in Advance.
Here is my full code
ImageButton playPause,lockScreen,unLock;
SeekBar seekBar;
TextView start,end;
boolean isPlaying = false;
boolean isLock = false;
RelativeLayout controller;
FrameLayout root;
boolean isControllerShowing = true;
private Handler mHandler;
SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
SessionManagement management;
String url, alternate;
Uri mp4VideoUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_tv);
checkConnection();
Sensey.getInstance().init(this);
Sensey.getInstance().startOrientationDetection(15,this);
management = new SessionManagement(this);
HashMap<String,String> hashMap = management.getUserDetails();
url = hashMap.get(SessionManagement.LIVE_URL);
alternate = hashMap.get(SessionManagement.ALTERNATE_URL);
playPause = findViewById(R.id.btnPlayPause);
lockScreen = findViewById(R.id.btnLock);
unLock = findViewById(R.id.btnOpenLock);
seekBar = findViewById(R.id.seeker);
end = findViewById(R.id.duration);
start = findViewById(R.id.position);
controller = findViewById(R.id.layout_controller);
root = findViewById(R.id.activity_live);
try {
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
simpleExoPlayerView = findViewById(R.id.video_view);
simpleExoPlayerView.setUseController(false);
simpleExoPlayerView.requestFocus();
simpleExoPlayerView.setPlayer(player);
mp4VideoUri = Uri.parse(url); //Radnom 540p indian channel
mHandler = new Handler();
DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
DefaultDataSourceFactory dataSourceFactory = new
DefaultDataSourceFactory(this, Util.getUserAgent(this, "Madha TV"), bandwidthMeterA);
DefaultExtractorsFactory();
dataSourceFactory, extractorsFactory, null, null);
MediaSource videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
player.prepare(loopingSource);
player.addListener(new ExoPlayer.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
switch (error.type) {
case ExoPlaybackException.TYPE_SOURCE:
Log.e("Error", "TYPE_SOURCE: " + error.getSourceException().getMessage());
Intent intent1 = new Intent(LiveTVActivity.this, MainActivity.class);
startActivity(intent1);
finish();
Toast.makeText(LiveTVActivity.this, error.getSourceException().getMessage(), Toast.LENGTH_SHORT).show();
break;
case ExoPlaybackException.TYPE_RENDERER:
break;
case ExoPlaybackException.TYPE_UNEXPECTED:
Log.e("Error", "TYPE_UNEXPECTED: " + error.getUnexpectedException().getMessage());
break;
}
player.stop();
player.prepare(loopingSource);
player.setPlayWhenReady(true);
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
player.setPlayWhenReady(true); //run file/link when ready to play.
player.setVideoDebugListener(this); //for listening to resolution change and outputing the resolution
if (player.getPlayWhenReady())
{
playPause.setImageResource(R.drawable.cvp_action_pause);
isPlaying = true;
}
else
{
playPause.setImageResource(R.drawable.cvp_action_play);
isPlaying = false;
}
root.setOnClickListener(this);
playPause.setOnClickListener(this);
lockScreen.setOnClickListener(this);
unLock.setOnClickListener(this);
}
catch (Exception e)
{
Log.e("Error",e.toString());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
updateMetadata();
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
updateMetadata();
}
}
#Override
public void onTopSideUp() {
updateMetadata();
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
#Override
public void onBottomSideUp() {
}
#Override
public void onRightSideUp() {
updateMetadata();
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onLeftSideUp() {
updateMetadata();
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
#SuppressWarnings("ConstantConditions")
private void updateMetadata() {
Point displaySize;
displaySize = Utils.getDisplaySize(this);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(displaySize.x,displaySize.y);
lp.gravity = Gravity.CENTER;
simpleExoPlayerView.setLayoutParams(lp);
simpleExoPlayerView.invalidate();
}
private void checkConnection()
{
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
if (!isConnected) {
Config.noConnection(LiveTVActivity.this);
}
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.btnPlayPause) {
setPlayPause();
}else if (view.getId() == R.id.btnLock) {
if (!isLock)
{
unLock.setVisibility(View.VISIBLE);
isLock = true;
controller.setVisibility(View.GONE);
root.setClickable(false);
}
}else if (view.getId() == R.id.btnOpenLock)
{
if (isLock)
{
root.setClickable(true);
isLock = false;
unLock.setVisibility(View.GONE);
controller.setVisibility(View.VISIBLE);
}
} else if (view.getId() == R.id.activity_live)
{
showController();
}
}
public void showController()
{
if (!isControllerShowing)
{
isControllerShowing = true;
controller.setVisibility(View.VISIBLE);
}
else
{
isControllerShowing = false;
controller.setVisibility(View.GONE);
}
}
private void setPlayPause() {
if (isPlaying)
{
player.setPlayWhenReady(false);
isPlaying = false;
playPause.setImageResource(R.drawable.cvp_action_play);
}
else
{
player.setPlayWhenReady(true);
isPlaying = true;
playPause.setImageResource(R.drawable.cvp_action_pause);
}
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
#Override
public void onVideoEnabled(DecoderCounters counters) {
}
#Override
public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {
}
#Override
public void onVideoInputFormatChanged(Format format) {
}
#Override
public void onDroppedFrames(int count, long elapsedMs) {
}
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
}
#Override
public void onRenderedFirstFrame(Surface surface) {
}
#Override
public void onVideoDisabled(DecoderCounters counters) {
}
Try this code..
public class VideoPlayerActivity extends AppCompatActivity implements ExoPlayer.EventListener {
private SimpleExoPlayer mSimpleExoPlayer;
private SimpleExoPlayerView mSimpleExoPlayerView;
private Handler mMainHandler;
private AdaptiveTrackSelection.Factory mAdaptiveTrackSelectionFactory;
private TrackSelector mTrackSelector;
private LoadControl mLoadControl;
private DefaultBandwidthMeter mBandwidthMeter;
private DataSource.Factory mDataSourceFactory;
private SimpleCache mSimpleCache;
private DataSource.Factory mFactory;
private MediaSource mVideoSource;
private LoopingMediaSource mLoopingMediaSource;
private ProgressBar mProgressBar;
private String videoUrl="http://sample.vodobox.net/skate_phantom_flex_4k/skate_phantom_flex_4k.m3u8";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
mSimpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.videoPlayer);
mProgressBar = (ProgressBar) findViewById(R.id.amPrgbrLoading);
}
/**
* this method play audio and video with hls streaming.
*/
private void playMedia() {
mMainHandler = new Handler();
mBandwidthMeter = new DefaultBandwidthMeter();
mAdaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(mBandwidthMeter);
mTrackSelector = new DefaultTrackSelector(mAdaptiveTrackSelectionFactory);
mLoadControl = new DefaultLoadControl();
mSimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, mTrackSelector, mLoadControl);
mSimpleExoPlayerView.setPlayer(mSimpleExoPlayer);
mSimpleExoPlayerView.setControllerVisibilityListener(new PlaybackControlView.VisibilityListener() {
#Override
public void onVisibilityChange(int visibility) {
mSimpleExoPlayerView.showController();
}
});
mDataSourceFactory = new DefaultDataSourceFactory(this,Util.getUserAgent(this, "com.exoplayerdemo"), mBandwidthMeter);
mSimpleCache = new SimpleCache(this.getCacheDir(), new LeastRecentlyUsedCacheEvictor(1024 * 1024 * 10));
mFactory = new CacheDataSourceFactory(mSimpleCache, mDataSourceFactory,0);
mVideoSource = new HlsMediaSource(Uri.parse(videoUrl),
mFactory, mMainHandler, new AdaptiveMediaSourceEventListener() {
#Override
public void onLoadStarted(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs) {
//Toast.makeText(VideoPlayerActivity.this, "Load Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onLoadCompleted(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded) {
//Toast.makeText(VideoPlayerActivity.this, "Load Completed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLoadCanceled(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded) {
}
#Override
public void onLoadError(DataSpec dataSpec, int dataType, int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs, long bytesLoaded, IOException error, boolean wasCanceled) {
videoUrl=""; // define second url
}
#Override
public void onUpstreamDiscarded(int trackType, long mediaStartTimeMs, long mediaEndTimeMs) {
// Toast.makeText(VideoPlayerActivity.this, "Up stream", Toast.LENGTH_SHORT).show();
}
#Override
public void onDownstreamFormatChanged(int trackType, Format trackFormat, int trackSelectionReason, Object trackSelectionData, long mediaTimeMs) {
// Toast.makeText(VideoPlayerActivity.this, "Down Stream", Toast.LENGTH_SHORT).show();
}
});
mLoopingMediaSource = new LoopingMediaSource(mVideoSource);
mSimpleExoPlayer.prepare(mLoopingMediaSource);
mSimpleExoPlayer.setPlayWhenReady(true);
mSimpleExoPlayer.addListener(new ExoPlayer.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_BUFFERING) {
mProgressBar.setVisibility(View.VISIBLE);
} else {
mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
});
}
#Override
protected void onResume() {
super.onResume();
playMedia();
}
#Override
protected void onStop() {
super.onStop();
stopMedia();
}
#Override
protected void onPause() {
super.onPause();
stopMedia();
}
private void stopMedia() {
mSimpleExoPlayer.stop();
mSimpleExoPlayer.release();
}
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
}
I am also getting the same issue. you have to do some change in your code
1. implement exo player listen to the activity so the common lister will use every instant of your player
Then you have to add all the player initialize code in a method and call this on error state of exo player
initializePlayer();
private void initializePlayer(String video_url) {
try {
videoUri = Uri.parse(VIDEOS_URL + contentMasterModel.getImage_or_video());
simpleExoPlayerView.requestFocus();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
simpleExoPlayerView.setPlayer(player);
//player.setPlayWhenReady(shouldAutoPlay);
player.addListener(this);
DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(videoUri,
mediaDataSourceFactory, extractorsFactory, null, null);
player.prepare(mediaSource);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
// Call some material design APIs here
// player.setPlayWhenReady(true);
}
inErrorState = false;
} catch (Exception e) {
e.printStackTrace();
Log.e("Please try again", "download again");
}
}
OnError
private void errorinitializePlayer() {
videoUri = Uri.parse(VIDEOS_URL);
simpleExoPlayerView.requestFocus();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
simpleExoPlayerView.setPlayer(player);
//player.setPlayWhenReady(shouldAutoPlay);
player.addListener(this);
DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(videoUri,
mediaDataSourceFactory, extractorsFactory, null, null);
player.prepare(mediaSource);
inErrorState = false;}
And implements EventListener, PlaybackControlView.VisibilityListener in activity

Stop exo player video from playing when exit from activity android

I am using Exo-Player.My video is playing fine but when i press back button and exit from activity my video keeps on playing in background.I don't how to stop it from playing when activity is finished.Please help
This is my code for exo player in recycler view adaptor
String my_date = data.get(position).getCreated_at();
String returneDate = setDateAndTime(my_date);
String img_url = data.get(position).getUser().getProfileUrl();
String videoUrl = data.get(position).getFile_url();
if (videoUrl != null) {
uri = Uri.parse(videoUrl);
} else {
holder.videoFrame.setVisibility(View.GONE);
}
holder.userVideoStatus.setText(data.get(position).getText());
holder.userNameVideoStatus.setText((CharSequence) data.get(position).getUser().getName());
holder.timeVideoStatus.setText(returneDate);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
player = ExoPlayerFactory.newSimpleInstance(activity, trackSelector);
DefaultHttpDataSourceFactory defaultHttpDataSourceFactory = new DefaultHttpDataSourceFactory("exo player");
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
final MediaSource mediaSource = new ExtractorMediaSource(uri, defaultHttpDataSourceFactory, extractorsFactory, null, null);
holder.playVideo.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
holder.playVideo.setVisibility(View.GONE);
holder.userVideoUpdate.setPlayer(player);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
holder.volumeUp.setVisibility(View.VISIBLE);
return true;
}
});
Ok Pavel B. gave the right answer but I am elaborating and making it clearer...
Adapter
public class ChatsAdapter extends RecyclerView {
public SimpleExoPlayer exoPlayer; // Do this at top
}
Activity
public class TestActivity extends AppCompatActivity {
private ChatsAdapter chatsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
chatsAdapter = new ChatsAdapter();
}
#Override
protected void onPause() {
super.onPause();
pausePlayer(chatsAdapter.exoPlayer);
}
#Override
protected void onStop() {
super.onStop();
pausePlayer(chatsAdapter.exoPlayer);
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseExoPlayer(chatsAdapter.exoPlayer);
}
#Override
protected void onResume() {
super.onResume();
startPlayer(chatsAdapter.exoPlayer);
}
public static void startPlayer(SimpleExoPlayer exoPlayer) {
if (exoPlayer != null) {
exoPlayer.setPlayWhenReady(true);
}
}
public static void pausePlayer(SimpleExoPlayer exoPlayer) {
if (exoPlayer != null) {
exoPlayer.setPlayWhenReady(false);
}
}
public static void releaseExoPlayer(SimpleExoPlayer exoPlayer) {
if (exoPlayer != null) {
exoPlayer.release();
}
}
}
in Your adapter - make player a public class member.
in Your activivty onStop() add:
yourAdapter.player.stopPlayback();
If you want to stop exoplayer , upgrade the latest Version of exoplayer and then try using
implementation 'com.google.android.exoplayer:exoplayer:2.14.2'
I tried using playerview.OnPause but that doesnt work .
player.setPlayWhenReady(true) - Used to Pause the player
player.setPlayWhenReady(false) - Used to Resume player .
Make sure you get the same instance of exoplayer everywhere , better if you can make a singleton class.

video doesnot play when we rotate Relativelayout containing Exoplayer

video doesnot play when we rotate Relativelayout containing Exoplayer
I have an activity containing Exoplayer. it works fine if we have the video in a relative layout , but when we rotate the relative layout , it doesnot play the video, how can this be done
here is the code for the activity
public class ExoplayerAct extends Activity implements VideoRendererEventListener {
private static final String TAG = "MainActivity";
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private TextView resolutionTextView;
String j;
RelativeLayout mainlayoutexo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exoplayer);
resolutionTextView = new TextView(this);
//resolutionTextView = (TextView) findViewById(R.id.resolution_textView);
Intent iin = getIntent();
Bundle b = iin.getExtras();
if (b != null) {
j = (String) b.get("fileVideoPath");
}
mainlayoutexo = (RelativeLayout) findViewById(R.id.mainlayoutexo);
mainlayoutexo.setRotation(90);
// 1. Create a default TrackSelector
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();
// 3. Create the player.newSimpleInstance(RenderersFactory, TrackSelector, LoadControl).
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
simpleExoPlayerView = new SimpleExoPlayerView(this);
simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
//Set media controller
simpleExoPlayerView.setUseController(true);
simpleExoPlayerView.requestFocus();
// Bind the player to the view.
simpleExoPlayerView.setPlayer(player);
Uri mp4VideoUri = Uri.parse(j);
//Measures bandwidth during playback. Can be null if not required.
DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
//Produces DataSource instances through which media data is loaded.
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this
, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeterA);
//Produces Extractor instances for parsing the media data.
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// II. ADJUST HERE:
//This is the MediaSource representing the media to be played:
//FOR SD CARD SOURCE:
MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, extractorsFactory, null, null);
//FOR LIVESTREAM LINK:
// MediaSource videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
// Prepare the player with the source.
player.prepare(loopingSource);
player.addListener(new ExoPlayer.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
Log.v(TAG, "Listener-onTimelineChanged...");
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
Log.v(TAG, "Listener-onTracksChanged...");
}
#Override
public void onLoadingChanged(boolean isLoading) {
Log.v(TAG, "Listener-onLoadingChanged...isLoading:"+isLoading);
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.v(TAG, "Listener-onPlayerStateChanged..." + playbackState);
}
#Override
public void onRepeatModeChanged(int repeatMode) {
Log.v(TAG, "Listener-onRepeatModeChanged...");
}
#Override
public void onPlayerError(ExoPlaybackException error) {
Log.v(TAG, "Listener-onPlayerError...");
player.stop();
player.prepare(loopingSource);
player.setPlayWhenReady(true);
}
#Override
public void onPositionDiscontinuity() {
Log.v(TAG, "Listener-onPositionDiscontinuity...");
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
Log.v(TAG, "Listener-onPlaybackParametersChanged...");
}
});
PlaybackParameters playbackParameters = new PlaybackParameters(2.0f, 1.0f);
player.setPlaybackParameters(playbackParameters);
player.setPlayWhenReady(true); //run file/link when ready to play.
player.setVideoDebugListener(this); //for listening to resolution change and outputing the resolution
}//End of onCreate
#Override
public void onVideoEnabled(DecoderCounters counters) {
}
#Override
public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {
}
#Override
public void onVideoInputFormatChanged(Format format) {
}
#Override
public void onDroppedFrames(int count, long elapsedMs) {
}
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
Log.v(TAG, "onVideoSizeChanged [" + " width: " + width + " height: " + height + "]");
resolutionTextView.setText("RES:(WxH):"+width+"X"+height +"\n "+height+"p");
}
#Override
public void onRenderedFirstFrame(Surface surface) {
}
#Override
public void onVideoDisabled(DecoderCounters counters) {
}
//-------------------------------------------------------ANDROID LIFECYCLE---------------------------------------------------------------------------------------------
#Override
protected void onStop() {
super.onStop();
Log.v(TAG, "onStop()...");
}
#Override
protected void onStart() {
super.onStart();
Log.v(TAG, "onStart()...");
}
#Override
protected void onResume() {
super.onResume();
Log.v(TAG, "onResume()...");
}
#Override
protected void onPause() {
super.onPause();
Log.v(TAG, "onPause()...");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy()...");
player.release();
}
}
and the layout is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="#+id/mainlayoutexo"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
android:id="#+id/player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/PlaybackControlViewa"
android:layout_marginTop="10dp"
android:focusable="true"
app:resize_mode="fit"
app:use_controller="false" />
<com.google.android.exoplayer2.ui.PlaybackControlView
android:id="#+id/PlaybackControlViewa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/bluebackground">
<ImageButton
android:id="#id/exo_play"
style="#style/ExoMediaButton.Play" />
<ImageButton
android:id="#id/exo_pause"
style="#style/ExoMediaButton.Pause" />
<com.google.android.exoplayer2.ui.DefaultTimeBar
android:id="#id/exo_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#F20000" />
</com.google.android.exoplayer2.ui.PlaybackControlView>
</RelativeLayout>
</RelativeLayout>
I just want to rotate the relative layout containing the exoplayer, how can this be done and video play with it
Im running the same code, and although the rotation dosnt have any handling, the video still runs when im switching between portrait and landscape. it pauses for a sec, then continues in the new orientation.
I get a warning in my logs but that's about expected.
can you post the logs that you get?
code came from :
https://github.com/ayalus/ExoPlayer-2-Example/tree/master/ExoPlayer2Example

how to stop audio playing in background in exoplayer

**
Need to implement video stream within a fragment using exoplayer. Streaming works fine but when moved from the fragment activity to other activity or if the screen is rotated, multiple copys of same audio plays in background continuously until the app is killed.how to handle this please help. Thanks in advance.
**
public class VideoFragment extends Fragment {
private SimpleExoPlayerView simpleExoPlayerView;
public SimpleExoPlayer player;
Uri mp4VideoUri;
String TAG ="LOGG";
SharedPrefs sharedPrefs;
TextView notavailable;
String url;
Connection connection;
long media_length;
public VideoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.video_fragment,container,false);
sharedPrefs = new SharedPrefs(getContext());
connection = new Connection(getContext());
notavailable= (TextView) rootView.findViewById(R.id.videonotavailable);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, loadControl);
simpleExoPlayerView = new SimpleExoPlayerView(getContext());
simpleExoPlayerView = (SimpleExoPlayerView) rootView.findViewById(R.id.player_view);
simpleExoPlayerView.setUseController(true);
simpleExoPlayerView.requestFocus();
simpleExoPlayerView.setPlayer(player);
DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "exoplayer2example"), bandwidthMeterA);
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
url=sharedPrefs.getvideoUrl();
if (url==null || url.equals("")){
simpleExoPlayerView.setVisibility(View.GONE);
notavailable.setVisibility(View.VISIBLE);
}else if (connection.isInternet()){
mp4VideoUri=Uri.parse(sharedPrefs.getvideoUrl());
MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri,dataSourceFactory,extractorsFactory,null,null);
final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
player.prepare(loopingSource);
player.addListener(new ExoPlayer.EventListener() {
#Override
public void onLoadingChanged(boolean isLoading) {
Log.v(TAG,"Listener-onLoadingChanged...");
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.v(TAG,"Listener-onPlayerStateChanged...");
}
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
Log.v(TAG,"Listener-onTimelineChanged...");
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
Log.v(TAG,"Listener-onPlayerError...");
player.stop();
}
#Override
public void onPositionDiscontinuity() {
Log.v("LOG","Listener-onPositionDiscontinuity...");
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
});
player.setPlayWhenReady(true);
}else {
simpleExoPlayerView.setVisibility(View.GONE);
notavailable.setVisibility(View.VISIBLE);
notavailable.setText(getString(R.string.nointernet));
}
return rootView;
}
#Override
public void onPause() {
super.onPause();
if(player != null) {
player.stop();
player.release();
media_length = player.getCurrentPosition();
}
}
#Override
public void onResume() {
super.onResume();
if(player != null) {
player.seekTo(media_length);
player.setPlayWhenReady(true);
}
}
}
In your fragment-holding activity, you need to handle the situation in the onPause method:
#Override
protected void onPause() {
super.onPause();
mPlayerFragment.pause();
}
You can define a method in your fragment to pause playback by passing false to setPlayWhenReady().
public void pausePlayback() {
mExoPlayer.setPlayWhenReady(false); //pauses the playback if it's playing
}
I am facing same issue and problem resolved after implement below code in my existing code
First You need to create global variable
boolean isActivityRunning = false;
Set this value in onCreate() and onResume() of activity to true.
You need to set Player if value isActivityRunning is true
After that you need to release player and set isActivityRunning = false in onPause(), onStop() and onDestroy() that look like
#Override
public void onPause() {
super.onPause();
isActivityRunning = false;
releasePlayer();
}
#Override
public void onStop() {
super.onStop();
isActivityRunning = false;
releasePlayer();
}
#Override
public void onBackPressed() {
super.onBackPressed();
releasePlayer();
}
#Override
protected void onDestroy(){
super.onDestroy();
releasePlayer();
}
and releasePlayer() implementation look like is
SimpleExoPlayer player;
PlayerView playerUI;
private void releasePlayer(){
if(player!=null){
player.release();
player.clearVideoSurface();
playerUI.getPlayer().release();;
player = null;
playerUI =null;
}
}
Where player and player UI is Global variable that need to set null
This solution work well for me.

Categories

Resources