How can I stream an online URL using MediaPlayer?
Basically, you need to do the following if you are using the Android MediaPlayer class:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
try {
mediaPlayer.setDataSource("http://someurl");
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
} catch (IOException e) {
}
Keep in mind the Android MediaPlayer class will only play supported formats: http://developer.android.com/guide/appendix/media-formats.html
Working for me in API 28
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("http://209.188.21.202:8016/stream");
mediaPlayer.prepare();
mediaPlayer.start();
Please Remember to add permissions to manifest if using INTERNET
<uses-permission android:name="android.permission.INTERNET" />
Also careful with usesCleartextTraffic
Starting with Android 9.0 (API level 28), cleartext support is disabled by default.
In my case I add --> android:usesCleartextTraffic="true" in manifest
Reference -->
Android 8: Cleartext HTTP traffic not permitted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With