Sunday, March 14, 2010

Play MediaPlayer with Authentication on Android

I was back to the Android lang with the free Nexus One from Google, and had a project in mind that involves MediaPlayer and for which here is how i did it.

private void playAudio(String mediaUrl) {
  try {
    URLConnection cn = new URL(mediaUrl).openConnection();
    cn.setRequestProperty("Your Header Name", "Your Header Value");
    InputStream is = cn.getInputStream();
    // create file to store audio
    File mediaFile = new File(this.getCacheDir(),"mediafile");
    FileOutputStream fos = new FileOutputStream(mediaFile);   
    byte buf[] = new byte[16 * 1024];
    // write to file until complete
    do {
      int numread = is.read(buf);   
      if (numread <= 0)  
        break;
      fos.write(buf, 0, numread);
    } while (true);
    fos.flush();
    fos.close();
    MediaPlayer mp = new MediaPlayer();
    // create listener to tidy up after playback complete
    MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener(){
      public void onCompletion(MediaPlayer mp) {
        // free up media player
        mp.release();
        Log.i("MediaPlayer.OnCompletionListener", "MediaPlayer Released");
      }
    };

    mp.setOnCompletionListener(listener);
    FileInputStream fis = new FileInputStream(mediaFile);
    mp.setDataSource(fis.getFD());
    mp.prepare();
    mp.start();
  } catch (Exception e) {
    e.printStackTrace();
  }
}


Explanation
First up this code came from http://stackoverflow.com/questions/1650983/server-side-aac-audio-with-android where it was the answer to a different question.

URLConnection cn = new URL(mediaUrl).openConnection();
cn.setRequestProperty("Your Header Name", "Your Header Value");

This is the core part and probably the only explanation beside the concept of the code that ill do. On here you create a URLConnection on where you can specify the request(headers) Property, depending on how you made the authentication on your server (say like GData) you can pass any headers related values.

Now on the concept, what the code does is like what it had said in stackoverflow, it downloads the music, outputs it to a FileOutputStream under the mediaFile File, where then we get to stream it to the FileInputStream which then we use as our data source on our MediaPlayer.

Hope this helps :)
Post a Comment