Can I use Basic HTTP Authentication with Android MediaPlayer?

前端 未结 5 1221
-上瘾入骨i
-上瘾入骨i 2021-01-24 08:29

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.         


        
相关标签:
5条回答
  • 2021-01-24 08:45

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

    0 讨论(0)
  • 2021-01-24 08:45

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

    http://<user>:<password>@<host>:<port>/<url-path>
    
    0 讨论(0)
  • 2021-01-24 08:54

    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/

    0 讨论(0)
  • 2021-01-24 09:03

    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)

    0 讨论(0)
  • 2021-01-24 09:09

    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();
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题