Thursday, January 31, 2013

Android Playing video from a web url

In android devices we can play a video from a web url in few simple steps. please make a project and have

VideoDemo.java


package com.jitesh.android.video;

import java.io.File;

import com.jitesh.android.video.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoDemo extends Activity {
private String videoPath = "http://commonsware.com/misc/test2.3gp";

private static ProgressDialog progressDialog;
String videourl;
VideoView videoView;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

videoView = (VideoView) findViewById(R.id.video);

progressDialog = ProgressDialog.show(VideoDemo.this, "",
"Buffering video...", true);
progressDialog.setCancelable(true);

PlayVideo();

}

private void PlayVideo() {
try {
getWindow().setFormat(PixelFormat.TRANSLUCENT);
MediaController mediaController = new MediaController(
VideoDemo.this);
mediaController.setAnchorView(videoView);

Uri video = Uri.parse(videoPath);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.requestFocus();
videoView.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
videoView.start();
}

});

} catch (Exception e) {
progressDialog.dismiss();
System.out.println("Video Play Error :" + e.toString());
finish();
}

}
}

the main.xml should look like this


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
  <VideoView 
     android:id="@+id/video" 
      android:layout_width="match_parent"
      android:layout_height="match_parent"
    />
</LinearLayout>

never forget the permission at manifest and add a line

 <uses-permission android:name="android.permission.INTERNET" />

the screen shot isbe shown here as well





the source code can be downloaded from hereVideoPlaying

No comments:

Post a Comment