GouravJn
GouravJn

Reputation: 256

Android media player: streaming audio file from HTTPS Url

I have to stream an audio file from Android media player from an application. Initially the file to be streamed was coming from a Http:// url and for which I was Using code-

public void playSample() {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected void onPreExecute() {
            mediaPlayer = new MediaPlayer();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                try {
                    mediaPlayer.setDataSource("http://an.http.url/");
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    Log.e("AudioFileError", "Could not open file for playback.", e);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            pd.dismiss();
        }
    };
    task.execute((Void[]) null);
}

This code is working as desired with http based file, but now the URL for Audio file was changed to https:// one(i.e., https://an.https.url/) and the code fails with an exception in

mediaPlayer.prepare();

The exception is

Prepare failed.: status=0x1

Please suggest a solution for it.

Upvotes: 2

Views: 4176

Answers (2)

Yogesh Rathi
Yogesh Rathi

Reputation: 6499

After long struggle i found solution,

Add below code before setDataSource().

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        sf.fixHttpsURLConnection();
        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    } catch (Exception e) {
        e.printStackTrace();
    }

#update1

Those who are using this answer, Read this caution from developer.android.com. Caution: Many web sites describe a poor alternative solution which is to install a TrustManager that does nothing. If you do this you might as well not be encrypting your communication, because anyone can attack your users at a public Wi-Fi hotspot by using DNS tricks to send your users' traffic through a proxy of their own that pretends to be your server

Upvotes: 1

Rajan Bhavsar
Rajan Bhavsar

Reputation: 1857

Media player in android <4.x supports only HTTP and 4.x n above support for BOTH http and https , so while using https with older API level, please think over it use http instead of https.

Upvotes: 1

Related Questions