-
-
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
.
dependencies {
implementation 'com.github.jrfeng.snow:exo:1.0.1'
}
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.
public class MyCustomPlayerService extends PlayerService {
private ProgressiveMediaSource.Factory mProgressiveMediaSourceFactory;
...
@Override
public void onCreate() {
...
mProgressiveMediaSourceFactory = new ProgressiveMediaSource.Factory(dataSourceFactory);
}
@NonNull
@Override
protected MusicPlayer onCreateMusicPlayer(@NonNull Context context, @NonNull MusicItem musicItem, @NonNull Uri uri) {
return new ExoMusicPlayer(context, mProgressiveMediaSourceFactory, 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()
.
Example:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpUtil.enableTls12OnPreLollipop(builder);
End