Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

Anyone that got any ideas?

like image 434
Vidar Vestnes Avatar asked Dec 20 '25 00:12

Vidar Vestnes


1 Answers

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();
        }
    });
}
like image 133
Lukas Lechner Avatar answered Dec 21 '25 13:12

Lukas Lechner