How to stream authenticated content with MediaPlayer on Android

江枫思渺然 提交于 2019-12-03 10:41:36

If you control the server, one option might be to modify it so that there's an option to generate a temporary, random URL for the content upon authentication, and then stream that. Will the streaming functions accept a URL that includes script parameters?

To do things entirely on the phone, another option would be to write a trivial http proxy like server in either java or native code and run it in a background thread. Instead of pointing the media player at the server, you'd point it at your own on-device proxy. The proxy would pass requests through to the remote server, while handling authentication.

One approach is to download the data yourself, decode it (from ??? to PCM) and use AudioTrack to play the PCM. The trick is in the decoding. What format is the stream encoded in?

The raw decoders for common protocols are available on the Android, but in C libraries. So you might have to add a JNI layer to do your decoding, again, depending on what encoding your stream is in.

SimonSimCity

I had the same problem, and I solved it by putting the credentials in the URL. It's not officially supported for HTTP, but most of the web-clients support it.

The code following is based on this tutorial: http://www.coderzheaven.com/2012/08/14/stream-audio-android/

    try {
        // You can use HTTPS or HTTP as protocol.
        String myURL = "https://example.com/song.mp3";

        mp.reset();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setOnPreparedListener(this);
        mp.setOnErrorListener(this);

        // These are the two lines, doing the magic ;) It transforms it to a url like this: https://user:password@example.com/song.mp3
        UsernamePasswordCredentials credentials = connHelper.getCredetials();
        myURL = myURL.replace("://", "://" + URLEncoder.encode(credentials.getUserName(), "UTF-8") + ":" + URLEncoder.encode(credentials.getPassword(), "UTF-8") + "@");

        mp.setDataSource(myURL);
        mp.prepareAsync();
        mp.setOnCompletionListener(this);
    } catch (Exception e) {
        Log.e("StreamAudioDemo", e.getMessage());
    }

NOTE: By using the URLEncoder here, we want to ungo problems like: If the username or password contains a colon or an @.

NOTE2: It may, or may not work for you, depending on your Server. If you run into that issue, I suggest you should take a look at that one: Why do browsers not send the Authentication header when the credentials are provided in the URL?

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