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
    • 10.1k
    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.

    1. public class Exoplayer {
    2.  
    3. private static Exoplayer mInstance = null;
    4. private static Exoplayer mAdsInstance = null;
    5. private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
    6. private String TAG = "Exoplayer";
    7. private SimpleExoPlayer player;
    8. SimpleExoPlayerView simpleExoPlayerView;
    9. DefaultDataSourceFactory dataSourceFactory;
    10. String uriString = "";
    11. ArrayList<String> playList = null;
    12. Integer playlistIndex = 0;
    13. CallBacks.playerCallBack listner;
    14.  
    15. public static Exoplayer getSharedInstance(Context mContext) {
    16. if (mInstance == null) {
    17. mInstance = new Exoplayer(mContext);
    18. }
    19. return mInstance;
    20. }
    21.  
    22. public static Exoplayer getSharedInstanceAds(Context mContext) {
    23. if (mAdsInstance == null) {
    24. mAdsInstance = new Exoplayer(mContext);
    25. }
    26. return mAdsInstance;
    27. }
    28.  
    29. private Exoplayer(Context mContext) {
    30.  
    31. TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
    32. TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    33. LoadControl loadControl = new DefaultLoadControl();
    34.  
    35. player = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector);
    36. simpleExoPlayerView = new SimpleExoPlayerView(mContext);
    37.  
    38. simpleExoPlayerView.setUseController(true);
    39. simpleExoPlayerView.requestFocus();
    40. simpleExoPlayerView.setPlayer(player);
    41.  
    42. Uri mp4VideoUri = Uri.parse(uriString);
    43.  
    44. dataSourceFactory = new DefaultDataSourceFactory(mContext, Util.getUserAgent(mContext, "exoplayer2example"), BANDWIDTH_METER);
    45. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
    46. final MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, new DefaultExtractorsFactory(),
    47. null, null);//new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
    48. // final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
    49.  
    50. player.prepare(videoSource);
    51. player.addListener(new ExoPlayer.EventListener() {
    52. @Override
    53. public void onTimelineChanged(Timeline timeline, Object manifest) {
    54. Log.v(TAG, "Listener-onTimelineChanged...");
    55. }
    56.  
    57. @Override
    58. public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
    59. Log.v(TAG, "Listener-onTracksChanged...");
    60.  
    61. }
    62.  
    63. @Override
    64. public void onLoadingChanged(boolean isLoading) {
    65. Log.v(TAG, "Listener-onLoadingChanged...isLoading:" + isLoading);
    66. }
    67.  
    68. @Override
    69. public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
    70. if (playbackState == 4 && playList != null && playlistIndex + 1 < playList.size()) {
    71. Log.e(TAG, "Song Changed...");
    72.  
    73. playlistIndex++;
    74. listner.onItemClickOnItem(playlistIndex);
    75. playStream(playList.get(playlistIndex));
    76. } else if (playbackState == 4 && playList != null && playlistIndex + 1 == playList.size()) {
    77. player.setPlayWhenReady(false);
    78. }
    79. if (playbackState == 4 && listner != null) {
    80. listner.onPlayingEnd();
    81. }
    82.  
    83. Log.v(TAG, "Listener-onPlayerStateChanged..." + playbackState);
    84. }
    85.  
    86. @Override
    87. public void onRepeatModeChanged(int repeatMode) {
    88.  
    89. }
    90.  
    91. @Override
    92. public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
    93.  
    94. }
    95.  
    96.  
    97. @Override
    98. public void onPlayerError(ExoPlaybackException error) {
    99. Log.v(TAG, "Listener-onPlayerError...");
    100. player.stop();
    101. player.prepare(videoSource);
    102. player.setPlayWhenReady(true);
    103. }
    104.  
    105. @Override
    106. public void onPositionDiscontinuity(int reason) {
    107.  
    108. }
    109.  
    110.  
    111. @Override
    112. public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
    113. Log.v(TAG, "Listener-onPlaybackParametersChanged...");
    114. }
    115.  
    116. @Override
    117. public void onSeekProcessed() {
    118.  
    119. }
    120. });
    121.  
    122.  
    123. }
    124.  
    125. public void setPlayerListener(CallBacks.playerCallBack ominaCallBack) {
    126. listner = ominaCallBack;
    127. }
    128.  
    129. public SimpleExoPlayerView getSimpleExoPlayerView() {
    130. return simpleExoPlayerView;
    131. }
    132.  
    133. public void playStream(String urlToPlay) {
    134. uriString = urlToPlay;
    135. Uri mp4VideoUri = Uri.parse(uriString);
    136. MediaSource videoSource;
    137. String filenameArray[] = urlToPlay.split("\\.");
    138. if (uriString.toUpperCase().contains("M3U8")) {
    139. videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, null, null);
    140. } else {
    141. mp4VideoUri = Uri.parse(urlToPlay);
    142. videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, new DefaultExtractorsFactory(),
    143. null, null);
    144. }
    145.  
    146.  
    147. // Prepare the player with the source.
    148. player.prepare(videoSource);
    149. player.setPlayWhenReady(true);
    150.  
    151. }
    152.  
    153. public void setplayerVolume(float vol) {
    154. player.setVolume(vol);
    155. }
    156.  
    157. public void setUriString(String uri) {
    158. uriString = uri;
    159. }
    160.  
    161. public void setPlaylist(ArrayList<String> uriArrayList, Integer index, CallBacks.playerCallBack callBack) {
    162. playList = uriArrayList;
    163. playlistIndex = index;
    164. listner = callBack;
    165. playStream(playList.get(playlistIndex));
    166. }
    167.  
    168.  
    169. public void playerPlaySwitch() {
    170. if (uriString != "") {
    171. player.setPlayWhenReady(!player.getPlayWhenReady());
    172. }
    173. }
    174.  
    175. public void stopPlayer(boolean state) {
    176. player.setPlayWhenReady(!state);
    177. }
    178.  
    179. public void destroyPlayer() {
    180. player.stop();
    181. }
    182.  
    183. public Boolean isPlayerPlaying() {
    184. return player.getPlayWhenReady();
    185. }
    186.  
    187. public ArrayList<String> readURLs(String url) {
    188. if (url == null) return null;
    189. ArrayList<String> allURls = new ArrayList<String>();
    190. try {
    191.  
    192. URL urls = new URL(url);
    193. BufferedReader in = new BufferedReader(new InputStreamReader(urls
    194. .openStream()));
    195. String str;
    196. while ((str = in.readLine()) != null) {
    197. allURls.add(str);
    198. }
    199. in.close();
    200. return allURls;
    201. } catch (Exception e) {
    202. e.printStackTrace();
    203. return null;
    204. }
    205. }
    206. }

     

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

    1. public class MainActivity extends AppCompatActivity {
    2. private String GRID_YOUTUBE_ID = "8saOHjoDX94";
    3. private String BASE_URL = "https://www.youtube.com";
    4. private String youtubeLink = BASE_URL + "/watch?v=" + GRID_YOUTUBE_ID;
    5.  
    6. @Override
    7. protected void onCreate(Bundle savedInstanceState) {
    8. super.onCreate(savedInstanceState);
    9. setContentView(R.layout.activity_main);
    10. extractYoutubeUrl();
    11. }
    12.  
    13. private void extractYoutubeUrl() {
    14. new YouTubeExtractor(this) {
    15. @Override
    16. public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
    17. if (ytFiles != null) {
    18. playVideo(ytFiles.get(17).getUrl());
    19. }
    20. }
    21. }.extract(youtubeLink, true, true);
    22. }
    23.  
    24. private void playVideo(String downloadUrl) {
    25. SimpleExoPlayerView simpleExoPlayer = findViewById(R.id.player);
    26. simpleExoPlayer.setPlayer(Exoplayer.getSharedInstance(MainActivity.this).getSimpleExoPlayerView().getPlayer());
    27. Exoplayer.getSharedInstance(MainActivity.this).playStream(downloadUrl);
    28. }
    29.  
    30.  
    31. }

     

    activity_main.xml 

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. tools:context="testdemo.com.test.MainActivity">
    8.  
    9.  
    10. <com.google.android.exoplayer2.ui.SimpleExoPlayerView
    11. android:id="@+id/player"
    12. android:layout_width="match_parent"
    13. android:layout_height="match_parent"></com.google.android.exoplayer2.ui.SimpleExoPlayerView>
    14. </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
Reset Password
Fill out the form below and reset your password: