Exoplayer2 hls - choose quality [duplicate] - android

I am currently developing a live and movie player application. I chose ExoPlayer version 2 to play the movie and I do not know much about it. I want to let the user choose the quality of a movie on the player screen, for example, 720p or 1080p or etc.
But I do not know how to get a list of existing qualities and show them to the user.
and the below code is my implementation of SimpleExoPlayer :
private void initPlayer(String path){
Handler handler = new Handler();
// 1. Create a default TrackSelector
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveVideoTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector =
new DefaultTrackSelector(videoTrackSelectionFactory);
// 2. Create a default LoadControl
LoadControl loadControl = new DefaultLoadControl();
// 3. Create the player
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
SimpleExoPlayerView playerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
playerView.setPlayer(player);
playerView.setKeepScreenOn(true);
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "ExoPlayer"));
// This is the MediaSource representing the media to be played.
MediaSource videoSource = new HlsMediaSource(Uri.parse(path),
dataSourceFactory,handler, null);
// Prepare the player with the source.
player.addListener(this);
player.prepare(videoSource);
playerView.requestFocus();
player.setPlayWhenReady(true); // to play video when ready. Use false to pause a video
}
// ExoPlayer Listener Methods :
#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) {
switch (playbackState) {
case ExoPlayer.STATE_BUFFERING:
//You can use progress dialog to show user that video is preparing or buffering so please wait
progressBar.setVisibility(View.VISIBLE);
break;
case ExoPlayer.STATE_IDLE:
//idle state
break;
case ExoPlayer.STATE_READY:
// dismiss your dialog here because our video is ready to play now
progressBar.setVisibility(GONE);
//Toast.makeText(getApplicationContext(),String.valueOf(player.getCurrentTrackSelections().get(0).getSelectedFormat().bitrate),Toast.LENGTH_SHORT).show();
break;
case ExoPlayer.STATE_ENDED:
// do your processing after ending of video
break;
}
}
#Override
public void onPlayerError(ExoPlaybackException error) {
// show user that something went wrong. it can be a dialog
}
#Override
public void onPositionDiscontinuity() {
}
please help to solve this issue.
thanks a lot.

Everything you'd like to achieve is viewable in the ExoPlayer2 demo app. More specifically the PlayerActivity class.
You can also check out this good article on the topic.
The core points you'll want to look into are around track selection (via the TrackSelector) as well as the TrackSelectionHelper. I'll include the important code samples below which will hopefully be enough to get you going. But ultimately just following something similar in the demo app will get you where you need to be.
You'll hold onto the track selector you init the player with and use that for just about everything.
Below is just a block of code to ideally cover the gist of what you're trying to do since the demo does appear to over-complicate things a hair. Also I haven't run the code, but it's close enough.
// These two could be fields OR passed around
int videoRendererIndex;
TrackGroupArray trackGroups;
// This is the body of the logic for see if there are even video tracks
// It also does some field setting
MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
for (int i = 0; i < mappedTrackInfo.length; i++) {
TrackGroupArray trackGroups = mappedTrackInfo.getTrackGroups(i);
if (trackGroups.length != 0) {
switch (player.getRendererType(i)) {
case C.TRACK_TYPE_VIDEO:
videoRendererIndex = i;
return true;
}
}
}
// This next part is actually about getting the list. It doesn't include
// some additional logic they put in for adaptive tracks (DASH/HLS/SS),
// but you can look at the sample for that (TrackSelectionHelper#buildView())
// Below you'd be building up items in a list. This just does
// views directly, but you could just have a list of track names (with indexes)
for (int groupIndex = 0; groupIndex < trackGroups.length; groupIndex++) {
TrackGroup group = trackGroups.get(groupIndex);
for (int trackIndex = 0; trackIndex < group.length; trackIndex++) {
if (trackIndex == 0) {
// Beginning of a new set, the demo app adds a divider
}
CheckedTextView trackView = ...; // The TextView to show in the list
// The below points to a util which extracts the quality from the TrackGroup
trackView.setText(DemoUtil.buildTrackName(group.getFormat(trackIndex)));
}
// Assuming you tagged the view with the groupIndex and trackIndex, you
// can build your override with that info.
Pair<Integer, Integer> tag = (Pair<Integer, Integer>) view.getTag();
int groupIndex = tag.first;
int trackIndex = tag.second;
// This is the override you'd use for something that isn't adaptive.
override = new SelectionOverride(FIXED_FACTORY, groupIndex, trackIndex);
// Otherwise they call their helper for adaptives, which roughly does:
int[] tracks = getTracksAdding(override, trackIndex);
TrackSelection.Factory factory = tracks.length == 1 ? FIXED_FACTORY : adaptiveTrackSelectionFactory;
override = new SelectionOverride(factory, groupIndex, tracks);
// Then we actually set our override on the selector to switch the quality/track
selector.setSelectionOverride(rendererIndex, trackGroups, override);
As I mentioned above, this is a slight oversimplification of the process, but the core part is that you're messing around with the TrackSelector, SelectionOverride, and Track/TrackGroups to get this to work.
You could conceivably copy the demo code verbatim and it should work, but I'd highly recommend taking the time to understand what each piece is doing and tailor your solution to your use case.
If I had more time I'd get it to compile and run. But if you can get my sample going then feel free to edit my post.
Hope that helps :)

I avoid the way as above posted. My way is using the DefaultTrackSelector as follows:
trackSelector.setParameters(trackSelector.getParameters()
.withMaxVideoBitrate(bitrate)
.withMaxVideoSize(width, height));
I've tested with HLS videos and it seems to perform in the right way. I get the bitrate, width and height reading from the HlsManifest.

You can copy the sample codes form this link.
ExoPlayer Video Quality Control.
Note : Do not forget to add the exoplayer dependencies in the built.gradle file
implementation 'com.google.android.exoplayer:exoplayer-core:2.16.1'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.16.1'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.16.1'
implementation 'com.google.android.exoplayer:exoplayer:2.16.1'

Related

RecyclerView with ExoPlayer/VideoView bad Performance

I want to play Videos in my RecyclerView Items, kind of like Instagram. There is only one Item expanded at a time so the Videos don't have to be played at the same time.
Im currently using the ExoPlayer. I have a PlayerView inside my item for the RecyclerView.
The problem is, with the Player I have bad performance which is very bad when scrolling and expanding. The Performany is already bad with just having the Player in the item without loading and playing a Video but it gets even worse with loading it.
I have tried VideoView too but it doesn't seem to make a big difference.
To achieve a better performance I already do:
recyclerView.setHasFixedSize(true);
recyclerView.setItemViewCacheSize(10);
recyclerView.setDrawingCacheEnabled(true);
recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
adapter.hasStableIds();
This helps a little bit but its doesn't solve the performance problem.
Any Idea what the problem can be? I appreciate and thoughts.
EDIT:
this is the method I setup the ExoPlayer:
public void showTutuorItems(Context context, Boolean show, String resource) {
if (show) {
seperator.setVisibility(View.VISIBLE);
lytTutor.setVisibility(View.VISIBLE);
playerView = itemView.findViewById(R.id.exoPlayer);
playerView.setUseController(false);
playerView = itemView.findViewById(R.id.exoPlayer);
playerView.setUseController(false);
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(context),
new DefaultTrackSelector(), new DefaultLoadControl());
playerView.setPlayer(player);
player.setPlayWhenReady(true);
player.seekTo(0, 0);
player.setRepeatMode(Player.REPEAT_MODE_ALL);
player.setVolume(0);
Uri uri = Uri.parse(resource);
MediaSource mediaSource = buildMediaSource(uri);
player.prepare(mediaSource, true, false);
player.addListener(new Player.EventListener() {
//...
}
} else {
seperator.setVisibility(View.GONE);
lytTutor.setVisibility(View.GONE);
}
}
private MediaSource buildMediaSource(Uri uri) {
return new ExtractorMediaSource.Factory(
new DefaultHttpDataSourceFactory("exoplayer-codelab")).
createMediaSource(uri);
}
and this is in my OnCreateViewHolder to call this method:
if (workout.getCurrentExercsise().getTutor() != null) {
holder.showTutuorItems(activity, true, workout.getCurrentExercsise().getTutor().getItems().get(0).getResource());
} else {
holder.showTutuorItems(activity, false, null);
}
In my OnBindViewHolder is some UI stuff and handling the expand/collapse function. This shouldn't cause the problem because without the ExoPlayer it works just fine.

Android Media Player Streaming not working

I have created one streaming audio application which is working on some Android devices but except moto g (6.0.1)API.
Exception: IOException OR MEDIA_ERROR_SYSTEM "error : (1, -2147483648)"
Code:
URL url = new URL("streaming extracted url");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String urlStr = uri.toASCIIString();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(urlStr);
player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
});
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
Can anyone please help me whats going wrong in this? Do I missing something?
I have had a similar and inexplicable issue. I am using a simple MediaPlayer to stream audio from a site. This works perfectly on a Samsung Galaxy S4 (Android 5.0.1), but on Pixel (Android 8.1.0) the audio won't play.
I am loading the URL on a play button click, showing a progress spinner until the MediaPlayer onPrepared listener is triggered. When prepared, I'm hiding the progress bar, and starting playback.
On Pixel, the normal loading / streaming time elapses (so I guess the file is being prepared!) onPrepared is triggered, no errors are shown, but the audio is never played!
Our server uses a self signed certificate which I thought might have been the issue, but even accessing the file over http it won't play on Pixel. I have also confirmed it's not a codec issue, as moving the file to Google Drive and playing with a direct link in my app the file plays back fine.
I am not sure if it's a server based issue, but all other files (images etc) are served and display fine (using Glide), and the file is served and can be viewed in Chrome via the same URL fed into the MediaPlayer!
I have just now moved to ExoPlayer, and it's playing fine on both devices .. so I guess this is the way forward!
Add dependency
compile 'com.google.android.exoplayer:exoplayer-core:2.6.1'
When play button is clicked, I'm loading Audio if not already loaded, otherwise starting playback
if (player == null) {
loadAudio();
} else {
player.setPlayWhenReady(true);
}
And my loadAudio()
private void loadAudio() {
String userAgent = Util.getUserAgent(getActivity(), "SimpleExoPlayer");
Uri uri = Uri.parse(audioUrl);
DataSource.Factory dataSourceFactory = new DefaultHttpDataSourceFactory(
userAgent, null,
DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
true);
// This is the MediaSource representing the media to be played.
MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
TrackSelector trackSelector = new DefaultTrackSelector();
player = ExoPlayerFactory.newSimpleInstance(getActivity(), trackSelector);
player.addListener(this);
player.prepare(mediaSource);
player.setPlayWhenReady(true);
}
... and the ExoPlayer listeners for state, so I can swap play / pause buttons in UI on completion etc
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_BUFFERING:
audioProgress.setVisibility(View.VISIBLE);
break;
case Player.STATE_ENDED:
handler.removeCallbacks(UpdateAudioTime);
buttonControllerPlay.setVisibility(View.VISIBLE);
buttonControllerPause.setVisibility(View.GONE);
seekBar.setProgress(0);
break;
case Player.STATE_IDLE:
break;
case Player.STATE_READY:
audioProgress.setVisibility(View.GONE);
finalTime = player.getDuration();
startTime = player.getCurrentPosition();
seekBar.setMax((int) finalTime);
seekBar.setProgress((int) startTime);
handler.postDelayed(UpdateAudioTime, 100);
break;
default:
break;
}
}
Remember to release the player on stop / destroy
Hopefully can help someone out there who is scratching their head as much as I was!
I've used the following code to stream audio on a Moto G5 (Android 7.0) and it is working fine:
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
mediaPlayer.setAudioAttributes(audioAttributes)
This might explain the issue:
Application developers should use audio attributes when creating or
updating applications for Android 5.0. However, applications are not
required to take advantage of attributes; they can handle legacy
stream types only or remain unaware of attributes (i.e. a generic
media player that doesn't know anything about the content it's
playing).
In such cases, the framework maintains backwards compatibility with
older devices and Android releases by automatically translating legacy
audio stream types to audio attributes. However, the framework does
not enforce or guarantee this mapping across devices, manufacturers,
or Android releases.
Source: https://source.android.com/devices/audio/attributes

Exoplayer not playing video only audio plays

ExoPlayer is not showing the video. I can listen the audio but video is not playing. I am using the Exoplayer in the Recyclerview.I only can see the black screen and listen to audio.I am not able to track the problem. I am playing the HLS video in the ExoPlayer.
I was also getting same issue few days back, now posting it here so that it can make someone's life easy since this problem appears very often when we use Exoplayer with RecyclerView.
Cause of the issue (in my case):
PlayerView was getting changed every time I came on the screen (due to the presence of RecyclerView)
I handled it by setting the player each time on the PlayerView object inside showLivePlayer() method which is called each time recycler view enabled screen opens to play the video.
public void showLivePlayer(PlayerView playerView, String videoURL, String tokenURL, ProgressBar progressBar){
mPlayerView = playerView;
if(player != null)
mPlayerView.setPlayer(player); //THIS IS THE FIX
mProgressBar = progressBar;
//register event bus
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
shouldAutoPlay = true;
bandwidthMeter = new DefaultBandwidthMeter();
mediaDataSourceFactory = new DefaultDataSourceFactory(mContext,
Util.getUserAgent(mContext, mContext.getString(R.string.app_name)), bandwidthMeter);
window = new Timeline.Window();
getLiveVideoToken(tokenURL, videoURL);
}
my bad was I was using PlayerControlView instead of PlayerView

ExoPlayer - play 10 files one after another

I have 10 video i need to play, once one is done, the next one starts to play.
I'm using Google's ExoPlayer, I use the example in the DEMO # GitHub.
I can play 1 video but if i try to play the next one, it wont start.
If i try to reInit the player, and the start playing again, it crashes.
private void loadvideo() {
Uri uri = Uri.parse(VIDEO_LIBRARY_URL + currentVideo + ".mp4");
sampleSource = new FrameworkSampleSource(this, uri, null, 2);
// 1. Instantiate the player.
// 2. Construct renderers.
videoRenderer = new MediaCodecVideoTrackRenderer(sampleSource, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource);
// 3. Inject the renderers through prepare.
player.prepare(videoRenderer, audioRenderer);
// 4. Pass the surface to the video renderer.
surface = surfaceView.getHolder().getSurface();
player.sendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface);
// 5. Start playback.
player.setPlayWhenReady(true);
player.addListener(new ExoPlayer.Listener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.d(TAG, "onPlayerStateChanged + " + playbackState);
if (playbackState == ExoPlayer.STATE_ENDED) {
currentVideo++;
loadNextVideo();
}
}
#Override
public void onPlayWhenReadyCommitted() {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
});
}
What am i doing wrong?
How can i play videos continuity?
Thanks.
You can reuse the ExoPlayer up until the point that you call release(), and then it should no longer be used.
To change the media that it is currently playing, you essentially need to perform the following steps:
// ...enable autoplay...
player.stop();
player.seekTo(0L);
player.prepare(renderers);
Creating the renderers is a little bit more involved, but that's the flow you should follow and the player should be able to play back to back videos.
I'm using Exoplayer change mp4 video success. I use the example in the DEMO.
1.DEMO project in DemoPlayer.java:
private final RendererBuilder rendererBuilder;
//remove final,then modify that:
private RendererBuilder rendererBuilder;
//and add the set method:
public void setRendererBuilder(RendererBuilder rendererBuilder){
this.rendererBuilder = rendererBuilder;
}
//finally,add stop method
public void stop(){
player.stop();
}
2.DEMO project in PlayerActivity.java:
add method:
private void changeVideo(){
player.stop();
player.seekTo(0L);
//you must change your contentUri before invoke getRendererBuilder();
player.setRendererBuilder(getRendererBuilder());
player.prepare();
playerNeedsPrepare = false;
}
remember change param contentUri before invoke changeVideo method.
Use ConcatenatingMediaSource to play files in sequence.
For example, for playing 2 media Uris (firstVideoUri and secondVideoUri), use this code:
MediaSource firstSource =
new ExtractorMediaSource.Factory(...).createMediaSource(firstVideoUri);
MediaSource secondSource =
new ExtractorMediaSource.Factory(...).createMediaSource(secondVideoUri);
ConcatenatingMediaSource concatenatedSource =
new ConcatenatingMediaSource(firstSourceTwice, secondSource);
And then use concatenatedSource to play media files sequentially.
OK, Answering my own question.
on the example, google init the ExoPlayer at OnResume().
i had to re-init for every video like that:
player = ExoPlayer.Factory.newInstance(2, 1000, 5000);
if someone has a better idea, please let me know.
There is another solution, you could refer to ConcatenatingMediaSource to achieve auto play next media.
In Demo App example :
1. Launch ExoPlayer
2. Select Playlists
3. Choose Cats->Dogs

Play audio and video at the same time in Android

I'm trying to play two different files at the same time.
I have tried to find players and tried to extend the default player achieving the same but couldn't get success in that. so please help me with it, by letting me know what's the best way to play audio file and video at the same time?
The reason I'm taking separate files is to save space, because the app will be localized, having multiple audio files for each language instead of having multiple videos saves space. That's important because android doesn't allow the download of app size above 50MB.
Any help in this would be extremely helpful. And providing me code for this would be a great help.
Thanks in advance.
You can handle this with Audio Focus. Two or more Android apps can play audio to the same output stream simultaneously. The system mixes everything together. While this is technically impressive, it can be very aggravating to a user. To avoid every music app playing at the same time, Android introduces the idea of audio focus. Only one app can hold audio focus at a time.
When your app needs to output audio, it should request audio focus. When it has focus, it can play sound. However, after you acquire audio focus you may not be able to keep it until you’re done playing. Another app can request focus, which preempts your hold on audio focus. If that happens your app should pause playing or lower its volume to let users hear the new audio source more easily.
Beginning with Android 8.0 (API level 26), when you call requestAudioFocus() you must supply an AudioFocusRequest parameter. To release audio focus, call the method abandonAudioFocusRequest() which also takes an AudioFocusRequest as its argument. The same AudioFocusRequest instance should be used when requesting and abandoning focus.
To create an AudioFocusRequest, use an AudioFocusRequest.Builder. Since a focus request must always specify the type of the request, the type is included in the constructor for the builder. Use the builder's methods to set the other fields of the request.
The following example shows how to use an AudioFocusRequest.Builder to build an AudioFocusRequest and request and abandon audio focus:
audioManager = (AudioManager) Context.getSystemService(Context.AUDIO_SERVICE);
playbackAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build();
focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(playbackAttributes)
.setAcceptsDelayedFocusGain(true)
.setOnAudioFocusChangeListener(afChangeListener, handler)
.build();
mediaPlayer = new MediaPlayer();
final Object focusLock = new Object();
boolean playbackDelayed = false;
boolean playbackNowAuthorized = false;
// ...
int res = audioManager.requestAudioFocus(focusRequest);
synchronized(focusLock) {
if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
playbackNowAuthorized = false;
} else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
playbackNowAuthorized = true;
playbackNow();
} else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
playbackDelayed = true;
playbackNowAuthorized = false;
}
}
// ...
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
if (playbackDelayed || resumeOnFocusGain) {
synchronized(focusLock) {
playbackDelayed = false;
resumeOnFocusGain = false;
}
playbackNow();
}
break;
case AudioManager.AUDIOFOCUS_LOSS:
synchronized(focusLock) {
resumeOnFocusGain = false;
playbackDelayed = false;
}
pausePlayback();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
synchronized(focusLock) {
resumeOnFocusGain = true;
playbackDelayed = false;
}
pausePlayback();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// ... pausing or ducking depends on your app
break;
}
}
}
Hope this helps! Also you can check Android's official documentation. If this doesn't help, you can check this site and this site for more documentation.
To play audio: Audio Track reference
To play video: Media Player reference
And now you could start on the main thread by showing in a Video View the video you want, and when is the time to play the sound you start playing the Audio Track. The tricky part will be to syncronize the audio with the video

Categories

Resources