2010. 7. 8. 01:46
모바일/안드로이드
출처 : http://www.tutorialforandroid.com/2010/03/play-mediaplayer-with-authentication-on.html
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 :)
'모바일 > 안드로이드' 카테고리의 다른 글
how to make mp4 for streaming (0) | 2010.07.13 |
---|---|
안드로이드 UI (0) | 2010.07.13 |
Audio and Video (0) | 2010.07.08 |
android mediaplayer (0) | 2010.07.08 |
Video Streaming with the Android Phone (0) | 2010.07.07 |