Can I use Basic HTTP Authentication with Android MediaPlayer?

穿精又带淫゛_ 提交于 2019-12-02 03:58:35

This worked for me:

    public void setupMediaPlayer(){

    // Setup Media Player and Prepare to Play
    media = new MediaPlayer();
    media.setAudioStreamType(AudioManager.STREAM_MUSIC);

    // Authdata
    String username = "username";
    String password = "password";

    // encrypt Authdata
    byte[] toEncrypt = (username + ":" + password).getBytes();
    String encoded = Base64.encodeToString(toEncrypt, Base64.DEFAULT);

    // create header
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization","Basic "+encoded);

    Uri uri = Uri.parse("http://your.full.url:port");

    try {
        media.setDataSource(this,uri,headers);
    } catch (IOException e) {
        Log.e(TAG,"Exception "+e.getMessage());
    }

    media.prepareAsync();

    media.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
}
Vidar Vestnes

I don't think the native media player supports this.

Have you tried putting the user ID and password in the URL?

http://<user>:<password>@<host>:<port>/<url-path>

You could download the mp3 on the cache and play it, here is a post on that http://almondmendoza.com/2010/03/11/play-mediaplayer-with-authentication-on-android/

You can pass HTTP headers, including basic auth headers, in MediaPlayer requests using the following method, which is available in Android API level 14 and above.

http://developer.android.com/reference/android/media/MediaPlayer.html#setDataSource(android.content.Context%2C%20android.net.Uri%2C%20java.util.Map%3Cjava.lang.String%2C%20java.lang.String%3E)

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