I am finding big differences in the time it takes the Android MediaPlayer to prepare for live stream playback with different streams.
The hard data<
When I had this problem I decided to test if stream is available before opening the player. If you make the user to wait for a long time and the music will start it ok (it's not, but let's say it is ok). The worst case scenario is to make him wait for a long time and the music will never start! So, we have 2 situations:
At the radio scenario we could check if the port is accepting connections (open/close state). If it is open prepare the player for the music, else do not prepare it at all.
public static boolean isLiveStreamingAvailable() {
SocketAddress sockaddr = new InetSocketAddress(STREAMING_HOST, STREAMING_PORT);
// Create your socket
Socket socket = new Socket();
boolean online = true;
// Connect with 10 s timeout
try {
socket.connect(sockaddr, 10000);
} catch (SocketTimeoutException stex) {
// treating timeout errors separately from other io exceptions
// may make sense
return false;
} catch (IOException iOException) {
return false;
} finally {
// As the close() operation can also throw an IOException
// it must caught here
try {
socket.close();
} catch (IOException ex) {
// feel free to do something moderately useful here, eg log the event
}
}
return true;
}
At the mp3 file scenario the things are a little bit different. You should check for the response code which follows after the http request.
public static boolean isRecordedStreamingAvailable() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(RECORDED_URL).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}