video doesnot play when we rotate Relativelayout containing Exoplayer - android

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

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)

Exoplayer audio playing background even video was closed

Below is My fragment that contains exoplayer which will inflate with draggable panel in Activity. My problem is while swiping the draggable panel left or right video is closing but audio is still playing in background. If I swipe off the draggable panel audio also needs to closed.Tried many sources couldn't found any solutions.Also In both fragment and Activity while swipping off the draggable panel onPause() method is not triggred. Also public void onClosedToLeft() method also not getting called.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dragpanelone, container, false);
try {
exoPlayerView = (SimpleExoPlayerView)v.findViewById(R.id.exoplayer);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
exoplayer = ExoPlayerFactory.newSimpleInstance(getActivity(), trackSelector);
Uri uri = Uri.parse(videoURL);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource mediaSource = new ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null);
exoPlayerView.setPlayer(exoplayer);
exoplayer.prepare(mediaSource);
exoplayer.setPlayWhenReady(true);
} catch (Exception e){
e.printStackTrace();
}
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
exoplayer.release();
}
#Override
public void onStop() {
super.onStop();
exoplayer.setPlayWhenReady(false);
}
public void pausePlayback() {
exoplayer.setPlayWhenReady(false); //pauses the playback if it's playing
}
private void releasePlayer() {
if (exoplayer != null) {
exoplayer.release();
exoplayer.setPlayWhenReady(false);
exoplayer = null;
}
}
public static void closePlayer()
{
exoplayer.clearVideoSurface();
}
}
This is my Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeDraggablepanel();
hookDraggablePanelListners();
}
public void initializeDraggablepanel(){
draggablepanel = (DraggablePanel)findViewById(R.id.draggable_panel);
draggablepanel.setFragmentManager(getSupportFragmentManager());
draggablepanel.setTopFragment(new DragpanelFragOne());
draggablepanel.setBottomFragment(new DragPanelTwo());
draggablepanel.setTopViewHeight(550);
draggablepanel.initializeView();
}
private void hookDraggablePanelListners(){
draggablepanel.setDraggableListener(new DraggableListener() {
#Override
public void onMaximized() {
}
#Override
public void onMinimized() {
}
#Override
public void onClosedToLeft() {
DragpanelFragOne.closePlayer();
Intent i = new Intent(MainActivity.this,HomeScreen.class);
startActivity(i);
}
#Override
public void onClosedToRight() {
DragpanelFragOne.closePlayer();
Intent i = new Intent(MainActivity.this,HomeScreen.class);
startActivity(i);
}
});
}
#Override
public void onPause() {
super.onPause();
DragpanelFragOne.closePlayer();
}
#Override
public void onStop() {
super.onStop();
draggablepanel.closeToLeft();
}
#Override
public void onBackPressed() {
draggablepanel.isClickToMinimizeEnabled();
Intent i = new Intent(MainActivity.this,HomeScreen.class);
startActivity(i);
}
}
Solution:
You need to call the method stop() on the exoplayer object whenever you are closing the player, like this:
if (exoPlayer != null) {
exoPlayer.setPlayWhenReady(false);
exoPlayer.stop();
exoPlayer.seekTo(0);
}
Hope this helps.

ExoPlayer resume on same position on rotate screen

I am using ExoPlayer in my activity,What i want is to smoothly play video in portrait and landscape mode.For this purpose what I am doing is in onpause I save the currentPlayerPosition and seek player to that position in onresume but while rotating it face a jerk and video is stopped for a while and played to the saved position.
My code is below please help me how i can smoothly switch the mode portrait and landscape.Thanks
#Override
public void onPause() {
super.onPause();
if (mExoPlayerView != null && mExoPlayerView.getPlayer() != null) {
mResumeWindow = mExoPlayerView.getPlayer().getCurrentWindowIndex();
mResumePosition = Math.max(0, mExoPlayerView.getPlayer().getContentPosition());
mExoPlayerView.getPlayer().release();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mExoPlayerView.getPlayer() != null)
mExoPlayerView.getPlayer().release();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_RESUME_WINDOW, mResumeWindow);
outState.putLong(STATE_RESUME_POSITION, mResumePosition);
outState.putBoolean(STATE_PLAYER_FULLSCREEN, mExoPlayerFullscreen);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
if (mExoPlayerView == null) {
mExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exoplayer);
videoURL = getIntent().getStringExtra("url");
postID = getIntent().getIntExtra("UserID", 0);
String userAgent = Util.getUserAgent(Vid.this, getApplicationContext().getApplicationInfo().packageName);
DefaultHttpDataSourceFactory httpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent, null, DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS, DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS, true);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(Vid.this, null, httpDataSourceFactory);
Uri daUri = Uri.parse(videoURL);
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
if (daUri.toString().startsWith("https://player.vimeo"))
mVideoSource = new HlsMediaSource(daUri, dataSourceFactory, 1, null, null);
else
mVideoSource = new ExtractorMediaSource(daUri, dataSourceFactory, extractorsFactory, null, null);
initExoPlayer();
} else {
resumeExoPlayer();
}
}
private void resumeExoPlayer() {
boolean haveResumePosition = mResumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
hideKeyboard();
hideProgress();
mExoPlayerView.getPlayer().seekTo(mResumeWindow, mResumePosition);
}
}
private void initExoPlayer() {
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), trackSelector, loadControl);
mExoPlayerView.setPlayer(player);
boolean haveResumePosition = mResumeWindow != C.INDEX_UNSET;
if (haveResumePosition) {
hideKeyboard();
hideProgress();
mExoPlayerView.getPlayer().seekTo(mResumeWindow, mResumePosition);
}
mExoPlayerView.getPlayer().prepare(mVideoSource);
mExoPlayerView.getPlayer().setPlayWhenReady(true);
mExoPlayerView.getPlayer().addListener(new Player.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_ENDED) {
hideProgress();
mExoPlayerView.getPlayer().seekTo(0);
mExoPlayerView.getPlayer().setPlayWhenReady(false);
} else if (playbackState == ExoPlayer.STATE_BUFFERING) {
} else if (playbackState == ExoPlayer.STATE_READY) {
hideProgress();
if (preferenceManager.getLoggedIn()) {
APIGetComment();
}
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
hideProgress();
finish();
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
Finally, After wasting 2 days I found it.
Simple add it in the manifest and will work on all android version ?
android:configChanges="orientation|screenSize|layoutDirection"
cheers!
If you want the video to resume on orientation change, you can add this to your manifest android:configChanges="keyboardHidden|orientation|screenSize"
<activity
<activity
android:name=".MainActivity"
android:name=".MainActivity"
android:label="#string/app_name"
android:label="#string/app_name"
+ android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="#style/AppTheme.NoActionBar"
android:theme="#style/AppTheme.NoActionBar"
android:icon="#mipmap/ic_launcher_2">
android:icon="#mipmap/ic_launcher_2">
<intent-filter>
<intent-filter>
No need of any additional coding, simply add this line
android:configChanges="keyboardHidden|orientation|screenSize"
in your AndroidManifest.xml's activity section.
I also wasted quite a lot time in this. Take a look at it EXO PLAYER 2.11.2
implementation 'com.google.android.exoplayer:exoplayer:2.11.2'
STEP - 1 Make an activity in which string url is passed as intent.
public class VideoPlayerActivity extends Activity {
public static final String sURL_KEY = "STREAMING_URL_KEY";
public static final String sTOAST_TEXT = "Unable to stream, no media found";
static final String LOADING = "PLAYER_LOADING";
static final String STOPPED = "PLAYER_STOPPED";
static final String PAUSED = "PLAYER_PAUSED";
static final String PLAYING = "PLAYER_PLAYING";
static final String IDLE = "PLAYER_IDLE";
private static final String TAG = "StreamMediaActivity";
int orientation;
private Uri streamUrl;
private SimpleExoPlayer mPlayer;
private PlayerView playerView;
private ProgressBar progressBar;
private String mPlayerStatus;
private long mPlaybackPosition = 0L;
private boolean mIsPlayWhenReady = true;
private int mCurrentWindow = 0;
private Display display;
private String STATE_RESUME_WINDOW = "resumeWindow";
private String STATE_RESUME_POSITION = "resumePosition";
private String STATE_PLAYER_FULLSCREEN = "playerFullscreen";
private boolean mExoPlayerFullscreen = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fullScreen();
display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
orientation = display.getRotation();
setContentView(R.layout.activity_video_player);
playerView = findViewById(R.id.player_view);
progressBar = findViewById(R.id.progressBar_player);
// Pass a string uri to this class
String urlString = getIntent().getStringExtra(sURL_KEY);
if (urlString != null) {
streamUrl = Uri.parse(urlString);
} else {
Toast.makeText(this, sTOAST_TEXT, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
super.onStart();
initPlayer();
}
#Override
protected void onResume() {
super.onResume();
if (mPlaybackPosition != 0L && mPlayer != null) {
mPlayer.seekTo(mCurrentWindow, mPlaybackPosition);
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override protected void onPause() {
super.onPause();
releasePlayer();
}
private void initPlayer() {
// ESTABLISH THE DATA SOURCE FROM URL
// here i'm playing local video file that's
// why using the DefaultDataSourceFactory but you
//may use DefaultHttpDataSourceFactory to stream
//online videos
DataSource.Factory dataSourceFactory =
new DefaultDataSourceFactory(this, Util.getUserAgent(this, getApplicationInfo().name));
MediaSource mediaSource =
new ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(
streamUrl);
// CREATE A NEW INSTANCE OF EXO PLAYER
if (mPlayer == null) {
mPlayer = new SimpleExoPlayer.Builder(this, new DefaultRenderersFactory(this)).build();
playerView.setPlayer(mPlayer);
progressBar.setVisibility(View.VISIBLE);
}
mPlayer.setPlayWhenReady(mIsPlayWhenReady);
mPlayer.seekTo(mCurrentWindow, mPlaybackPosition);
// PREPARE MEDIA PLAYER
mPlayer.prepare(mediaSource, true, false);
mPlayer.addListener(new Player.EventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_BUFFERING:
mPlayerStatus = LOADING;
runOnUiThread(() -> progressBar.setVisibility(View.VISIBLE));
break;
case Player.STATE_ENDED:
mPlayerStatus = STOPPED;
break;
case Player.STATE_READY:
mPlayerStatus = (playWhenReady) ? PLAYING : PAUSED;
runOnUiThread(() -> progressBar.setVisibility(View.INVISIBLE));
break;
default:
mPlayerStatus = IDLE;
break;
}
}
#Override
public void onPlayerError(ExoPlaybackException error) {
Toast.makeText(VideoPlayerActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
finish();
}
});
}
#Override protected void onSaveInstanceState(Bundle outState) {
mExoPlayerFullscreen = !mExoPlayerFullscreen;
super.onSaveInstanceState(outState);
outState.putInt(STATE_RESUME_WINDOW, mCurrentWindow);
outState.putLong(STATE_RESUME_POSITION, mPlaybackPosition);
outState.putBoolean(STATE_PLAYER_FULLSCREEN, mExoPlayerFullscreen);
super.onSaveInstanceState(outState);
}
public void fullScreen() {
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
}
private void releasePlayer() {
if (mPlayer != null) {
mPlayer.stop();
mPlaybackPosition = mPlayer.getCurrentPosition();
mCurrentWindow = mPlayer.getCurrentWindowIndex();
mIsPlayWhenReady = mPlayer.getPlayWhenReady();
playerView.setPlayer(null);
mPlayer.release();
mPlayer = null;
}
}
}
Step 2 : Make the XML layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<FrameLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.exoplayer2.ui.PlayerView
android:id="#+id/player_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
android:keepScreenOn="true"
app:use_controller="true"
app:resize_mode="fit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ProgressBar
android:id="#+id/progressBar_player"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
STEP 3: start VideoPlayerActivity using intent from another activity
Intent streamVideoIntent = new Intent(context, VideoPlayerActivity.class);
streamVideoIntent.putExtra(sURL_KEY, stringUrl);
context.startActivity(streamVideoIntent);
STEP 4 : Lastly add activity to manifest
<activity android:name=".ui.videoplayer.VideoPlayerActivity"
android:configChanges="orientation|screenSize|layoutDirection"
/>

How to play a particular video from ExoPlayer playlist 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();

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