-
-
Notifications
You must be signed in to change notification settings - Fork 45
[EN] 5.Use ExoPlayer
The exo
module provides an implementation of MusicPlayer
based on ExoPlayer
: ExoMusicPlayer
.
Note
:exo
module requireminSdkVersion 21
, if you need to supportAPI 16
, please useexo-api16
module instead.
dependencies {
// require minSdkVersion 21
implementation 'com.github.jrfeng.snow:exo:1.2'
// For API 16:
// implementation 'com.github.jrfeng.snow:exo-api16:1.2'
}
Enable Java 8:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
The constructor of ExoMusicPlayer
:
public ExoMusicPlayer(@NonNull Context context, @NonNull Uri uri)
public ExoMusicPlayer(@NonNull Context context, @NonNull MediaItem mediaItem)
public ExoMusicPlayer(@NonNull Context context, @NonNull MediaSourceFactory mediaSourceFactory, @NonNull Uri uri)
Note: The exo
module only adds dependencies on ExoPlayer's exoplayer-core
and extension-okhttp
modules. If you want to use other functions of ExoPlayer
, you need to add dependencies on the corresponding modules yourself. For details, please check the ExoPlayer Doc
.
The custom MusicPlayer
needs to be applied by inheriting PlayerService
and overriding its onCreateMusicPlayer(Context, MusicItem, Uri)
method.
@PersistenId("MyPlayerService")
public MyPlayerService extends PlayerService {
...
@NonNull
@Override
protected MusicPlayer onCreateMusicPlayer(@NonNull Context context, @NonNull MusicItem musicItem, @NonNull Uri uri) {
return new ExoMusicPlayer(context, uri);
}
}
More details, see Custom PlayerService.
By default, ExoPlayer does not allow cross-protocol redirection, such as http -> https
or https -> http
.
If you need to enable cross-protocol redirection, you can refer to the following code:
DefaultHttpDataSourceFactory httpDataSourceFactory =
new DefaultHttpDataSourceFactory(
Util.getUserAgent(context, context.getPackageName()),
null,
DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
true/*allow cross-protocol redirection*/);
DefaultDataSourceFactory dataSourceFactory =
new DefaultDataSourceFactory(context, httpDataSourceFactory);
This is because below API level 20 do not enable TLS v1.2
by default. Solution: https://github.com/square/okhttp/issues/2372#issuecomment-244807676
Based on this solution, the exo
module provides an OkHttpUtil
. Just use your OkHttpClient.Builder
instance invoke the static method OkHttpUtil.enableTls12OnPreLollipop(OkHttpClient.Builder builder)
.
Example:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpUtil.enableTls12OnPreLollipop(builder);
End