Android media player: streaming audio file from HTTPS Url

别来无恙 提交于 2021-02-07 04:15:17

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/30166725/android-media-player-streaming-audio-file-from-https-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!