Skip to content Skip to sidebar Skip to footer

Can I Use Basic Http Authentication With Android Mediaplayer?

I cant find a way to use an url that requires basic auth when im useing mp.setDataSource(url); MediaPlayer mp = new MediaPlayer(); mp.setDataSource(url); mp.prepareAsync(); An

Solution 1:

This worked for me:

publicvoidsetupMediaPlayer(){

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

    // AuthdataString username = "username";
    String password = "password";

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

    // create headerMap<String, String> headers = newHashMap<>();
    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(newMediaPlayer.OnPreparedListener() {
        publicvoidonPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
}

Solution 2:

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

Solution 3:

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

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

Solution 4:

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/

Solution 5:

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)

Post a Comment for "Can I Use Basic Http Authentication With Android Mediaplayer?"