Play video in android app from project resource...

           In this application we will play a video in our own app from the project resources.It is very easy to do. First of all make a simple xml layout containing a videoview and a button. When we will press the button video will start. So please collect a .3gp video and save it in raw folder under res folder. In our project we take the video name as test.3gp.
          So, here is the xml layout for this...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PLAY" />

        <VideoView
            android:id="@+id/videoView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
   

</LinearLayout>
Now we will write the java code to make the button working and start the video. Check it carefully.
package com.myandroid.videoPlayer;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoPlayActivity extends Activity
{
Button btPlay;
VideoView vv;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btPlay=(Button)findViewById(R.id.button1);
        vv=(VideoView)findViewById(R.id.videoView1);
        btPlay.setOnClickListener(new OnClickListener()
        {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
playVideo();

}

private void playVideo()
{
getWindow().setFormat(PixelFormat.TRANSLUCENT);
VideoView videoHolder = new VideoView(VedioPlayActivity.this);
videoHolder.setMediaController(new MediaController(VedioPlayActivity.this));
Uri video = Uri.parse("android.resource://" + getPackageName() + "/"  + R.raw.test);
videoHolder.setVideoURI(video);
setContentView(videoHolder);
videoHolder.start();

}
});
   
    }
}
Please note, this code will work on android 2.3.3 or higher(api 10 or higher).

No comments:

Post a Comment