一.背景
最近公司让研究一个exoplayer播放器,所以在网上找了些资料,记录一下。英语不错的同学可以直接看文档(
点击打开链接) 另外附上官方的github地址(
https://github.com/google/ExoPlayer)
二.步骤
- 添加exoplayer的依赖
- 创建simpleExoplayer实例
- 将播放器和SimpleExoplayerView结合
- 用MediaSource准备播放
- 结束播放释放资源
三.具体代码
public class MainActivity extends AppCompatActivity {
private Context mContext;
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer simpleExoPlayer;
private DataSource.Factory dataSourceFactory;
private EventLogger eventLogger;
private Handler mainHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
init();
}
private void init() {
// 1 create a default TrackSelector
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
// 打印日志
eventLogger = new EventLogger(trackSelector);
// 2. Create the player
simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector);
// bind the player to the view
simpleExoPlayerView.setPlayer(simpleExoPlayer);
// 默认带宽测量
DefaultBandwidthMeter defaultBandwidthMeter =
new DefaultBandwidthMeter();
dataSourceFactory =
new DefaultDataSourceFactory(mContext,
Util.getUserAgent(mContext, "ExoPlayerDemo"), defaultBandwidthMeter);
Uri uri = Uri.parse("http://devimages.apple.com/samplecode/adDemo/ad.m3u8");
MediaSource mediaSource = new HlsMediaSource(uri, dataSourceFactory, mainHandler, eventLogger);
// 准备播放
simpleExoPlayer.prepare(mediaSource);
// 自动播放
simpleExoPlayer.setPlayWhenReady(true);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (simpleExoPlayer != null) {
simpleExoPlayer.release();
}
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wxj.exoplayer.MainActivity" >
<com.google.android.exoplayer2.ui.SimpleExoPlayerView
android:id="@+id/player_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
依赖文件,我这里依赖的全部的,其实你可以选择一两个就行
compile 'com.google.android.exoplayer:exoplayer-core:r2.5.1'
compile 'com.google.android.exoplayer:exoplayer-dash:r2.5.1'
compile 'com.google.android.exoplayer:exoplayer-ui:r2.5.1'
compile 'com.google.android.exoplayer:exoplayer-hls:r2.5.1'
compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.5.1'
最后不要忘记加网络的权限