Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Extract YOUTUBE Video URL and Play Using Exoplayer

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 1
    • 0
    • 9.93k
    Comment on it

    Exoplayer is an open source application level media player for Android. For playing audio/video both locally and through internet this media player is very good and alternative source for Android's Media Player API along with features like Dynamic adaptive streaming over HTTP (DASH), SmoothStreaming and Common Encryption.

     

     

    So, in this blog, I will show you How to Extract any Youtube Video URL and Play it in the Background as well using My Custom Exoplayer class.

     

    Below is the custom Exoplayer class to play the video.

    public class Exoplayer {
    
        private static Exoplayer mInstance = null;
        private static Exoplayer mAdsInstance = null;
        private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
        private String TAG = "Exoplayer";
        private SimpleExoPlayer player;
        SimpleExoPlayerView simpleExoPlayerView;
        DefaultDataSourceFactory dataSourceFactory;
        String uriString = "";
        ArrayList<String> playList = null;
        Integer playlistIndex = 0;
        CallBacks.playerCallBack listner;
    
        public static Exoplayer getSharedInstance(Context mContext) {
            if (mInstance == null) {
                mInstance = new Exoplayer(mContext);
            } 
            return mInstance;
        }
    
        public static Exoplayer getSharedInstanceAds(Context mContext) {
            if (mAdsInstance == null) {
                mAdsInstance = new Exoplayer(mContext);
            }
            return mAdsInstance;
        }
    
        private Exoplayer(Context mContext) {
    
            TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
            TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
            LoadControl loadControl = new DefaultLoadControl();
    
            player = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector);
            simpleExoPlayerView = new SimpleExoPlayerView(mContext);
    
            simpleExoPlayerView.setUseController(true);
            simpleExoPlayerView.requestFocus();
            simpleExoPlayerView.setPlayer(player);
    
            Uri mp4VideoUri = Uri.parse(uriString);
    
            dataSourceFactory = new DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, "exoplayer2example"), BANDWIDTH_METER);
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
            final MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, new DefaultExtractorsFactory(),
                    null, null);//new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
    //        final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
    
            player.prepare(videoSource);
            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) {
                    if (playbackState == 4 && playList != null && playlistIndex + 1 < playList.size()) {
                        Log.e(TAG, "Song Changed...");
    
                        playlistIndex++;
                        listner.onItemClickOnItem(playlistIndex);
                        playStream(playList.get(playlistIndex));
                    } else if (playbackState == 4 && playList != null && playlistIndex + 1 == playList.size()) {
                        player.setPlayWhenReady(false);
                    }
                    if (playbackState == 4 && listner != null) {
                        listner.onPlayingEnd();
                    }
    
                    Log.v(TAG, "Listener-onPlayerStateChanged..." + playbackState);
                }
    
                @Override
                public void onRepeatModeChanged(int repeatMode) {
    
                }
    
                @Override
                public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
    
                }
    
    
                @Override
                public void onPlayerError(ExoPlaybackException error) {
                    Log.v(TAG, "Listener-onPlayerError...");
                    player.stop();
                    player.prepare(videoSource);
                    player.setPlayWhenReady(true);
                }
    
                @Override
                public void onPositionDiscontinuity(int reason) {
    
                }
    
    
                @Override
                public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
                    Log.v(TAG, "Listener-onPlaybackParametersChanged...");
                }
    
                @Override
                public void onSeekProcessed() {
    
                }
            });
    
    
        }
    
        public void setPlayerListener(CallBacks.playerCallBack ominaCallBack) {
            listner = ominaCallBack;
        }
    
        public SimpleExoPlayerView getSimpleExoPlayerView() {
            return simpleExoPlayerView;
        }
    
        public void playStream(String urlToPlay) {
            uriString = urlToPlay;
            Uri mp4VideoUri = Uri.parse(uriString);
            MediaSource videoSource;
            String filenameArray[] = urlToPlay.split("\\.");
            if (uriString.toUpperCase().contains("M3U8")) {
                videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, null, null);
            } else {
                mp4VideoUri = Uri.parse(urlToPlay);
                videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, new DefaultExtractorsFactory(),
                        null, null);
            }
    
    
    // Prepare the player with the source.
            player.prepare(videoSource);
            player.setPlayWhenReady(true);
    
        }
    
        public void setplayerVolume(float vol) {
            player.setVolume(vol);
        }
    
        public void setUriString(String uri) {
            uriString = uri;
        }
    
        public void setPlaylist(ArrayList<String> uriArrayList, Integer index, CallBacks.playerCallBack callBack) {
            playList = uriArrayList;
            playlistIndex = index;
            listner = callBack;
            playStream(playList.get(playlistIndex));
        }
    
    
        public void playerPlaySwitch() {
            if (uriString != "") {
                player.setPlayWhenReady(!player.getPlayWhenReady());
            }
        }
    
        public void stopPlayer(boolean state) {
            player.setPlayWhenReady(!state);
        }
    
        public void destroyPlayer() {
            player.stop();
        }
    
        public Boolean isPlayerPlaying() {
            return player.getPlayWhenReady();
        }
    
        public ArrayList<String> readURLs(String url) {
            if (url == null) return null;
            ArrayList<String> allURls = new ArrayList<String>();
            try {
    
                URL urls = new URL(url);
                BufferedReader in = new BufferedReader(new InputStreamReader(urls
                        .openStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    allURls.add(str);
                }
                in.close();
                return allURls;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    

     

    MainActivity.java is the activity class where we going to extract youtube url  and play it using our custom Exoplayer.

    public class MainActivity extends AppCompatActivity {
        private String GRID_YOUTUBE_ID = "8saOHjoDX94";
        private String BASE_URL = "https://www.youtube.com";
        private String youtubeLink = BASE_URL + "/watch?v=" + GRID_YOUTUBE_ID;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            extractYoutubeUrl();
        }
    
        private void extractYoutubeUrl() {
            new YouTubeExtractor(this) {
                @Override
                public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
                    if (ytFiles != null) {
                        playVideo(ytFiles.get(17).getUrl());
                    }
                }
            }.extract(youtubeLink, true, true);
        }
    
        private void playVideo(String downloadUrl) {
            SimpleExoPlayerView simpleExoPlayer = findViewById(R.id.player);
            simpleExoPlayer.setPlayer(Exoplayer.getSharedInstance(MainActivity.this).getSimpleExoPlayerView().getPlayer());
            Exoplayer.getSharedInstance(MainActivity.this).playStream(downloadUrl);
        }
    
    
    }

     

    activity_main.xml 

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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"
        tools:context="testdemo.com.test.MainActivity">
    
    
        <com.google.android.exoplayer2.ui.SimpleExoPlayerView
            android:id="@+id/player"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></com.google.android.exoplayer2.ui.SimpleExoPlayerView>
    </android.support.constraint.ConstraintLayout>
    Extract YOUTUBE Video URL and Play Using Exoplayer

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: