Category Archives: android-mediaplayer

Stream mp3 from protected directory in Android app

I have a problem with streaming mp3 file from protected directory on server. To protect directory I use simple .htaccess

AuthType Basic
AuthUserFile /home/domains/.htpasswd
require valid-user
AuthName "Protected directory"

To stream the mp3 I try to use sth like this:

        MediaPlayer mediaPlayer=new MediaPlayer();

        Context context=getContext();
        Uri myUri1 = Uri.parse("http:/user:[email protected]/uploads/ABC.mp3");

        try {
            mediaPlayer.setDataSource(context, myUri1);
        } catch (IllegalArgumentException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mediaPlayer.prepare();
        } catch (IllegalStateException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
        }
        mediaPlayer.start();

Of course when I use this url in browser everything work fine. Any ideas how to fix this?