1 Adding ExoPlayer as a dependency
Add repositories
在项目根目录的build.gradle中添加:
repositories {
google()
jcenter() }
Add ExoPlayer modules
在App的build.gradle中添加:
implementation ‘com.google.android.exoplayer:exoplayer:2.X.X’
2.X.X是exoplayer的版本,可以根据需要选择。版本号可以在这里查询。
上面添加的是整个exoplayer库,也可以只添加需要的模块。
implementation ‘com.google.android.exoplayer:exoplayer-core:2.X.X’
implementation ‘com.google.android.exoplayer:exoplayer-dash:2.X.X’
implementation ‘com.google.android.exoplayer:exoplayer-ui:2.X.X’
implementation ‘com.google.android.exoplayer:exoplayer-hls:2.X.X’
implementation ‘com.google.android.exoplayer:exoplayer-smoothstreaming:2.X.X’
Turn on Java 8 support
如果enable失败,在所有依赖Exoplayer模块的build.gradle中添加JAVA 8支持
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
}
2 Creating the player
可以用SimpleExoPlayer.Builder或ExoPlayer.Builder创建一个ExoPlayer实例。
SimpleExoPlayer player = new SimpleExoPlayer.Builder(context).build();
A note on threading
必须从单个应用程序线程访问ExoPlayer实例。在绝大多数情况下,这应该是应用程序的主线程。使用ExoPlayer的UI组件或IMA扩展程序时,必须使用应用程序的主线程。
创建播放器时,可以通过传递Looper来明确指定必须访问ExoPlayer实例的线程。如果未指定Looper,则使用创建播放器的线程的Looper,或者如果该线程没有Looper,则使用应用程序主线程的Looper。在所有情况下,都可以使用Player.getApplicationLooper查询必须从其访问播放器的线程的Looper。
如果看到“Player is accessed on the wrong thread”警告,则表明应用程序中的某些代码正在错误的线程上访问SimpleExoPlayer实例(记录的堆栈跟踪显示了您的位置!)。这是不安全的,并且可能导致意外或模糊的错误。
3 Attaching the player to a view
在layout中添加PlayerView, 然后在onCreate中findViewById
playerView = findViewById(R.id.video_view);
绑定playerView和player
// Bind the player to the view.
playerView.setPlayer(player);
4 Preparing the player
根据URI创建MediaSource
// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new
DefaultDataSourceFactory(context,
Util.getUserAgent(context, “yourApplicationName”)); // This is the MediaSource representing the media to be played. MediaSource
videoSource =
new ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(mp4VideoUri); // Prepare the player with the source.
然后调用prepare方法
player.prepare(videoSource);
5 Controlling the player
prepare调用后就可以通过PlayView中的PlayerContrlView控件控制视频播放了。也可以通过start/pause/seekTo等方法在代码中控制。
6 Releasing the player
使用完后通过release方法释放
player.release()