当前位置:   article > 正文

ExoPlayer的使用介绍

simpleexoplayer如何重置播放器

版权声明:本文为博主原创文章,转载请注明出处。 推荐: 欢迎关注我创建的Android TV 简书专题,会定期给大家分享一些AndroidTV相关的内容:Android TV


前言:ExoPlayer是google推出的一个应用级的播放框架。接下来我来对它做一个简单的介绍。 ###一,为什么是ExoPlayer? 1.支持更多的格式 我们知道Android 提供的mediaPlayer只支持有限的格式,比如视频,它支持MP4,3GP。想要播放其他格式的视频还要进行相应的转换。ExoPlayer提供了强大的格式支持。 ExoPlayer支持的媒体格是在多个级别定义的。 从最低层到最高层,分别是:

  • 单个媒体样本的格式(例如,视频帧或音频帧)。 我们称这些样本格式 。 请注意,典型的视频文件将包含至少两种样本格式的媒体; 一个用于视频(例如,H.264)和一个用于音频(例如,AAC)。
  • 容纳媒体样本和相关元数据的容器的格式。 我们称这些容器格式 。 媒体文件具有单个容器格式(例如MP4),通常由文件扩展名指示。 请注意,对于某些仅音频格式(例如MP3),样本和容器格式可能相同。
  • 自适应流技术,如DASH,SmoothStreaming和HLS。 这些不是媒体格式,但是仍然需要定义什么级别的支持ExoPlayer提供。

2.ExoPlayer是java语言编写的,相比与MediaPlayer用Native Code来说,可以更清楚的获得一些异常源和进行部分代码调试。 3.ExoPlayer是开源的,github上地址ExoPlayer遇到问题后可以提交Issues,最近遇到关于SimpleExoPlayer setVideoListener去监听OnVideoSizeChanged()时黑屏有声音,然后提交了一个Issues:The surface show nothing after mSimpleExoPlayer.setVideoListener(mVideoListener),他们很快给了回复,另外开源的代码经过大家的验证,也会更加的健壮。 4.ExoPlayer有强大的开发文档developer guide ,读者也可以根据文档更好的了解它。 ###二,如何使用? 这里演示一个播放器的简单使用。 ####1.在xml中

  1. <LinearLayout
  2. android:id="@+id/activity_main"
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:orientation="vertical"
  8. tools:context="com.songwenju.useexoplayer.MainActivity">
  9. <com.google.android.exoplayer2.ui.SimpleExoPlayerView
  10. android:id="@+id/exoView"
  11. android:layout_width="match_parent"
  12. android:layout_height="match_parent">
  13. <ProgressBar
  14. android:id="@+id/progressBar"
  15. android:visibility="gone"
  16. style="?android:attr/progressBarStyleLarge"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:layout_gravity="center"/>
  20. </com.google.android.exoplayer2.ui.SimpleExoPlayerView>
  21. </LinearLayout>
  22. 复制代码

这里使用了SimpleExoPlayerView,在其内部添加了一个ProgressBar。 ####2.播放需要的步骤 初始化播放器:

  1. /**
  2. * 初始化player
  3. */
  4. private void initPlayer() {
  5. //1. 创建一个默认的 TrackSelector
  6. BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
  7. TrackSelection.Factory videoTackSelectionFactory =
  8. new AdaptiveTrackSelection.Factory(bandwidthMeter);
  9. TrackSelector trackSelector =
  10. new DefaultTrackSelector(videoTackSelectionFactory);
  11. LoadControl loadControl = new DefaultLoadControl();
  12. //2.创建ExoPlayer
  13. mSimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this,trackSelector,loadControl);
  14. //3.创建SimpleExoPlayerView
  15. mExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exoView);
  16. //4.为SimpleExoPlayer设置播放器
  17. mExoPlayerView.setPlayer(mSimpleExoPlayer);
  18. }
  19. 复制代码

开始播放:

  1. private void playVideo() {
  2. //测量播放过程中的带宽。 如果不需要,可以为null。
  3. DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
  4. // 生成加载媒体数据的DataSource实例。
  5. DataSource.Factory dataSourceFactory
  6. = new DefaultDataSourceFactory(MainActivity.this,
  7. Util.getUserAgent(MainActivity.this,"useExoplayer"),bandwidthMeter);
  8. // 生成用于解析媒体数据的Extractor实例。
  9. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
  10. // MediaSource代表要播放的媒体。
  11. MediaSource videoSource = new ExtractorMediaSource(playerUri,dataSourceFactory,extractorsFactory,
  12. null,null);
  13. //Prepare the player with the source.
  14. mSimpleExoPlayer.prepare(videoSource);
  15. //添加监听的listener
  16. // mSimpleExoPlayer.setVideoListener(mVideoListener);
  17. mSimpleExoPlayer.addListener(eventListener);
  18. // mSimpleExoPlayer.setTextOutput(mOutput);
  19. mSimpleExoPlayer.setPlayWhenReady(true);
  20. }
  21. 复制代码

监听播放器的状态:

  1. private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {
  2. @Override
  3. public void onTimelineChanged(Timeline timeline, Object manifest) {
  4. LogUtil.i(this,"onTimelineChanged");
  5. }
  6. @Override
  7. public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
  8. LogUtil.i(this,"onTracksChanged");
  9. }
  10. @Override
  11. public void onLoadingChanged(boolean isLoading) {
  12. LogUtil.i(this,"onLoadingChanged");
  13. }
  14. @Override
  15. public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
  16. LogUtil.i(this,"onPlayerStateChanged: playWhenReady = "+String.valueOf(playWhenReady)
  17. +" playbackState = "+playbackState);
  18. switch (playbackState){
  19. case ExoPlayer.STATE_ENDED:
  20. LogUtil.i(this,"Playback ended!");
  21. //Stop playback and return to start position
  22. setPlayPause(false);
  23. mSimpleExoPlayer.seekTo(0);
  24. break;
  25. case ExoPlayer.STATE_READY:
  26. mProgressBar.setVisibility(View.GONE);
  27. LogUtil.i(this,"ExoPlayer ready! pos: "+mSimpleExoPlayer.getCurrentPosition()
  28. +" max: "+stringForTime((int)mSimpleExoPlayer.getDuration()));
  29. setProgress(0);
  30. break;
  31. case ExoPlayer.STATE_BUFFERING:
  32. LogUtil.i(this,"Playback buffering!");
  33. mProgressBar.setVisibility(View.VISIBLE);
  34. break;
  35. case ExoPlayer.STATE_IDLE:
  36. LogUtil.i(this,"ExoPlayer idle!");
  37. break;
  38. }
  39. }
  40. @Override
  41. public void onPlayerError(ExoPlaybackException error) {
  42. LogUtil.i(this,"onPlaybackError: "+error.getMessage());
  43. }
  44. @Override
  45. public void onPositionDiscontinuity() {
  46. LogUtil.i(this,"onPositionDiscontinuity");
  47. }
  48. @Override
  49. public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
  50. LogUtil.i(this,"MainActivity.onPlaybackParametersChanged."+playbackParameters.toString());
  51. }
  52. };
  53. 复制代码
  1. mSimpleExoPlayer.addListener(eventListener);
  2. 复制代码

通过监听状态去显示loading条,做错误处理等。

Activity退出时,释放播放器:

  1. @Override
  2. protected void onPause() {
  3. LogUtil.i(this,"MainActivity.onPause.");
  4. super.onPause();
  5. mSimpleExoPlayer.stop();
  6. }
  7. @Override
  8. protected void onStop() {
  9. LogUtil.i(this,"MainActivity.onStop.");
  10. super.onStop();
  11. mSimpleExoPlayer.release();
  12. }
  13. 复制代码

MainActivity完整的代码

  1. public class MainActivity extends AppCompatActivity {
  2. private SimpleExoPlayerView mExoPlayerView;
  3. private SimpleExoPlayer mSimpleExoPlayer;
  4. private Context mContext;
  5. Uri playerUri = Uri.parse("https://storage.googleapis.com/android-tv/Sample%20videos/Demo%20Slam/Google%20Demo%20Slam_%20Hangin'%20with%20the%20Google%20Search%20Bar.mp4");
  6. private ProgressBar mProgressBar;
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. requestWindowFeature(Window.FEATURE_NO_TITLE);
  11. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  12. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  13. setContentView(R.layout.activity_main);
  14. mContext = this;
  15. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  16. initPlayer();
  17. playVideo();
  18. }
  19. /**
  20. * 初始化player
  21. */
  22. private void initPlayer() {
  23. //1. 创建一个默认的 TrackSelector
  24. BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
  25. TrackSelection.Factory videoTackSelectionFactory =
  26. new AdaptiveTrackSelection.Factory(bandwidthMeter);
  27. TrackSelector trackSelector =
  28. new DefaultTrackSelector(videoTackSelectionFactory);
  29. LoadControl loadControl = new DefaultLoadControl();
  30. //2.创建ExoPlayer
  31. mSimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this,trackSelector,loadControl);
  32. //3.创建SimpleExoPlayerView
  33. mExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exoView);
  34. //4.为SimpleExoPlayer设置播放器
  35. mExoPlayerView.setPlayer(mSimpleExoPlayer);
  36. }
  37. private void playVideo() {
  38. //测量播放过程中的带宽。 如果不需要,可以为null。
  39. DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
  40. // 生成加载媒体数据的DataSource实例。
  41. DataSource.Factory dataSourceFactory
  42. = new DefaultDataSourceFactory(MainActivity.this,
  43. Util.getUserAgent(MainActivity.this,"useExoplayer"),bandwidthMeter);
  44. // 生成用于解析媒体数据的Extractor实例。
  45. ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
  46. // MediaSource代表要播放的媒体。
  47. MediaSource videoSource = new ExtractorMediaSource(playerUri,dataSourceFactory,extractorsFactory,
  48. null,null);
  49. //Prepare the player with the source.
  50. mSimpleExoPlayer.prepare(videoSource);
  51. //添加监听的listener
  52. // mSimpleExoPlayer.setVideoListener(mVideoListener);
  53. mSimpleExoPlayer.addListener(eventListener);
  54. // mSimpleExoPlayer.setTextOutput(mOutput);
  55. mSimpleExoPlayer.setPlayWhenReady(true);
  56. }
  57. TextRenderer.Output mOutput = new TextRenderer.Output() {
  58. @Override
  59. public void onCues(List<Cue> cues) {
  60. LogUtil.i(this,"MainActivity.onCues.");
  61. }
  62. };
  63. private SimpleExoPlayer.VideoListener mVideoListener = new SimpleExoPlayer.VideoListener() {
  64. @Override
  65. public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
  66. LogUtil.i(this,"MainActivity.onVideoSizeChanged.width:"+width+", height:"+height);
  67. }
  68. @Override
  69. public void onRenderedFirstFrame() {
  70. LogUtil.i(this,"MainActivity.onRenderedFirstFrame.");
  71. }
  72. };
  73. private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {
  74. @Override
  75. public void onTimelineChanged(Timeline timeline, Object manifest) {
  76. LogUtil.i(this,"onTimelineChanged");
  77. }
  78. @Override
  79. public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
  80. LogUtil.i(this,"onTracksChanged");
  81. }
  82. @Override
  83. public void onLoadingChanged(boolean isLoading) {
  84. LogUtil.i(this,"onLoadingChanged");
  85. }
  86. @Override
  87. public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
  88. LogUtil.i(this,"onPlayerStateChanged: playWhenReady = "+String.valueOf(playWhenReady)
  89. +" playbackState = "+playbackState);
  90. switch (playbackState){
  91. case ExoPlayer.STATE_ENDED:
  92. LogUtil.i(this,"Playback ended!");
  93. //Stop playback and return to start position
  94. setPlayPause(false);
  95. mSimpleExoPlayer.seekTo(0);
  96. break;
  97. case ExoPlayer.STATE_READY:
  98. mProgressBar.setVisibility(View.GONE);
  99. LogUtil.i(this,"ExoPlayer ready! pos: "+mSimpleExoPlayer.getCurrentPosition()
  100. +" max: "+stringForTime((int)mSimpleExoPlayer.getDuration()));
  101. setProgress(0);
  102. break;
  103. case ExoPlayer.STATE_BUFFERING:
  104. LogUtil.i(this,"Playback buffering!");
  105. mProgressBar.setVisibility(View.VISIBLE);
  106. break;
  107. case ExoPlayer.STATE_IDLE:
  108. LogUtil.i(this,"ExoPlayer idle!");
  109. break;
  110. }
  111. }
  112. @Override
  113. public void onPlayerError(ExoPlaybackException error) {
  114. LogUtil.i(this,"onPlaybackError: "+error.getMessage());
  115. }
  116. @Override
  117. public void onPositionDiscontinuity() {
  118. LogUtil.i(this,"onPositionDiscontinuity");
  119. }
  120. @Override
  121. public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
  122. LogUtil.i(this,"MainActivity.onPlaybackParametersChanged."+playbackParameters.toString());
  123. }
  124. };
  125. /**
  126. * Starts or stops playback. Also takes care of the Play/Pause button toggling
  127. * @param play True if playback should be started
  128. */
  129. private void setPlayPause(boolean play){
  130. mSimpleExoPlayer.setPlayWhenReady(play);
  131. }
  132. private String stringForTime(int timeMs) {
  133. StringBuilder mFormatBuilder;
  134. Formatter mFormatter;
  135. mFormatBuilder = new StringBuilder();
  136. mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
  137. int totalSeconds = timeMs / 1000;
  138. int seconds = totalSeconds % 60;
  139. int minutes = (totalSeconds / 60) % 60;
  140. int hours = totalSeconds / 3600;
  141. mFormatBuilder.setLength(0);
  142. if (hours > 0) {
  143. return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
  144. } else {
  145. return mFormatter.format("%02d:%02d", minutes, seconds).toString();
  146. }
  147. }
  148. @Override
  149. protected void onPause() {
  150. LogUtil.i(this,"MainActivity.onPause.");
  151. super.onPause();
  152. mSimpleExoPlayer.stop();
  153. }
  154. @Override
  155. protected void onStop() {
  156. LogUtil.i(this,"MainActivity.onStop.");
  157. super.onStop();
  158. mSimpleExoPlayer.release();
  159. }
  160. }
  161. 复制代码

gitHub实例:useExoPlayer。 关注微信公众号,定期为你推荐移动开发相关文章。

转载于:https://juejin.im/post/5b714cb9e51d45667851dc8a

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/299320
推荐阅读
相关标签
  

闽ICP备14008679号