TUTORIAL Membuat Aplikasi Video Recorder Sederhana di Android

selamat pagi semua, kali ini saya akan memberikan sedikit tutorial singkat tentang membuat aplikasi video record pada android.
mungkin dari aplikasi yang masih sederhana ini teman" bisa mengimprove nya lagi menjadi lebih bagus lagi.

berikut langkah" nya
-pertama buat project dengan nama VideoCaptureDemo
-lalu selanjutnya beri nama package nya dengan nama saung.it.video
-nah setelah selesai kita langsung masuk ke inti, membuat kelas
-klo saya sendiri membuat main kelas nya di rename dengan nama VideoCaptureActivity tapi teserah gmna enaknya









berikut source dari class VideoCaptureActivity

package saung.it.video;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.marakana.android.videocapturedemo.R;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

public class VideoCaptureActivity extends Activity {
    private static final String TAG = "VideoCaptureActivity";

    Camera camera;

    ImageButton recordButton;

    ImageButton stopButton;

    FrameLayout cameraPreviewFrame;

    CameraPreview cameraPreview;

    MediaRecorder mediaRecorder;

    File file;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        super.setContentView(R.layout.video_capture);
        this.cameraPreviewFrame = (FrameLayout)super.findViewById(R.id.camera_preview);
        this.recordButton = (ImageButton)super.findViewById(R.id.recordButton);
        this.stopButton = (ImageButton)super.findViewById(R.id.stopButton);
        this.toggleButtons(false);
        // we'll enable this button once the camera is ready
        this.recordButton.setEnabled(false);
    }

    void toggleButtons(boolean recording) {
        this.recordButton.setEnabled(!recording);
        this.recordButton.setVisibility(recording ? View.GONE : View.VISIBLE);
        this.stopButton.setEnabled(recording);
        this.stopButton.setVisibility(recording ? View.VISIBLE : View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // initialize the camera in background, as this may take a while
        new AsyncTask<Void, Void, Camera>() {

            @Override
            protected Camera doInBackground(Void... params) {
                try {
                    Camera camera = Camera.open();
                    return camera == null ? Camera.open(0) : camera;
                } catch (RuntimeException e) {
                    Log.wtf(TAG, "Failed to get camera", e);
                    return null;
                }
            }

            @Override
            protected void onPostExecute(Camera camera) {
                if (camera == null) {
                    Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record,
                            Toast.LENGTH_SHORT);
                } else {
                    VideoCaptureActivity.this.initCamera(camera);
                }
            }
        }.execute();
    }

    void initCamera(Camera camera) {
        // we now have the camera
        this.camera = camera;
        // create a preview for our camera
        this.cameraPreview = new CameraPreview(VideoCaptureActivity.this, this.camera);
        // add the preview to our preview frame
        this.cameraPreviewFrame.addView(this.cameraPreview, 0);
        // enable just the record button
        this.recordButton.setEnabled(true);
    }

    void releaseCamera() {
        if (this.camera != null) {
            this.camera.lock(); // unnecessary in API >= 14
            this.camera.stopPreview();
            this.camera.release();
            this.camera = null;
            this.cameraPreviewFrame.removeView(this.cameraPreview);
        }
    }

    void releaseMediaRecorder() {
        if (this.mediaRecorder != null) {
            this.mediaRecorder.reset(); // clear configuration (optional here)
            this.mediaRecorder.release();
            this.mediaRecorder = null;
        }
    }

    void releaseResources() {
        this.releaseMediaRecorder();
        this.releaseCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        this.releaseResources();
    }

    // gets called by the button press
    public void startRecording(View v) {
        Log.d(TAG, "startRecording()");
        // we need to unlock the camera so that mediaRecorder can use it
        this.camera.unlock(); // unnecessary in API >= 14
        // now we can initialize the media recorder and set it up with our
        // camera
        this.mediaRecorder = new MediaRecorder();
        this.mediaRecorder.setCamera(this.camera);
        this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        this.mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        this.mediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
        this.mediaRecorder.setPreviewDisplay(this.cameraPreview.getHolder().getSurface());
        try {
            this.mediaRecorder.prepare();
            // start the actual recording
            // throws IllegalStateException if not prepared
            this.mediaRecorder.start();
            Toast.makeText(this, R.string.recording, Toast.LENGTH_SHORT).show();
            // enable the stop button by indicating that we are recording
            this.toggleButtons(true);
        } catch (Exception e) {
            Log.wtf(TAG, "Failed to prepare MediaRecorder", e);
            Toast.makeText(this, R.string.cannot_record, Toast.LENGTH_SHORT).show();
            this.releaseMediaRecorder();
        }
    }

    // gets called by the button press
    public void stopRecording(View v) {
        Log.d(TAG, "stopRecording()");
        assert this.mediaRecorder != null;
        try {
            this.mediaRecorder.stop();
            Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
            // we are no longer recording
            this.toggleButtons(false);
        } catch (RuntimeException e) {
            // the recording did not succeed
            Log.w(TAG, "Failed to record", e);
            if (this.file != null && this.file.exists() && this.file.delete()) {
                Log.d(TAG, "Deleted " + this.file.getAbsolutePath());
            }
            return;
        } finally {
            this.releaseMediaRecorder();
        }
        if (this.file == null || !this.file.exists()) {
            Log.w(TAG, "File does not exist after stop: " + this.file.getAbsolutePath());
        } else {
            Log.d(TAG, "Going to display the video: " + this.file.getAbsolutePath());
            Intent intent = new Intent(this, VideoPlaybackActivity.class);
            intent.setData(Uri.fromFile(file));
            super.startActivity(intent);
        }
    }

    private File initFile() {
        File dir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), this
                        .getClass().getPackage().getName());
        if (!dir.exists() && !dir.mkdirs()) {
            Log.wtf(TAG, "Failed to create storage directory: " + dir.getAbsolutePath());
            Toast.makeText(VideoCaptureActivity.this, R.string.cannot_record, Toast.LENGTH_SHORT);
            this.file = null;
        } else {
            this.file = new File(dir.getAbsolutePath(), new SimpleDateFormat(
                    "'IMG_'yyyyMMddHHmmss'.m4v'").format(new Date()));
        }
        return this.file;
    }
}



-Selanjutnya buat kelas baru dengan nama VideoPlaybackActivity
di class ini fungsinya adalah untuk memberikan fungsi" yang ada di aplikasi video recorder

package saung.it.video;

import java.io.File;

import com.marakana.android.videocapturedemo.R;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.VideoView;

public class VideoPlaybackActivity extends Activity implements OnPreparedListener,
        OnCompletionListener {
    private static final String TAG = "VideoPlaybackActivity";

    private VideoView videoView;

    private ImageButton backButton;

    private ImageButton playButton;

    private ImageButton stopButton;

    private ImageButton deleteButton;

    private Uri uri;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        super.setContentView(R.layout.video_playback);
        this.videoView = (VideoView)super.findViewById(R.id.video);
        this.uri = super.getIntent().getData();
        this.backButton = (ImageButton)super.findViewById(R.id.backButton);
        this.playButton = (ImageButton)super.findViewById(R.id.playButton);
        this.stopButton = (ImageButton)super.findViewById(R.id.stopButton);
        this.deleteButton = (ImageButton)super.findViewById(R.id.deleteButton);
    }

    private void toggleButtons(boolean playing) {
        this.backButton.setEnabled(!playing);
        this.playButton.setVisibility(playing ? View.GONE : View.VISIBLE);
        this.stopButton.setVisibility(playing ? View.VISIBLE : View.GONE);
        this.deleteButton.setEnabled(!playing);
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.videoView.setVideoURI(this.uri);
        this.videoView.setOnPreparedListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        this.videoView.stopPlayback();
    }

    public void onPrepared(MediaPlayer mp) {
        Log.d(TAG, "Prepared. Subscribing for completion callback.");
        this.videoView.setOnCompletionListener(this);
        Log.d(TAG, "Starting plackback");
        this.videoView.start();
        Toast.makeText(this, R.string.playing, Toast.LENGTH_SHORT).show();
        this.toggleButtons(true);
    }

    public void onCompletion(MediaPlayer mp) {
        Log.d(TAG, "Completed playback. Go to beginning.");
        this.videoView.seekTo(0);
        this.notifyUser(R.string.completed_playback);
        this.toggleButtons(false);
    }

    // gets called by the button press
    public void back(View v) {
        Log.d(TAG, "Going back");
        super.finish();
    }

    // gets called by the button press
    public void play(View v) {
        Log.d(TAG, "Playing");
        this.videoView.start();
        this.toggleButtons(true);
    }

    public void stop(View v) {
        Log.d(TAG, "Stopping");
        this.videoView.pause();
        this.videoView.seekTo(0);
        this.toggleButtons(false);
    }

    // gets called by the button press
    public void delete(View v) {
        if (new File(this.uri.getPath()).delete()) {
            Log.d(TAG, "Deleted: " + this.uri);
            this.notifyUser(R.string.deleted);
        } else {
            Log.d(TAG, "Failed to delete: " + this.uri);
            this.notifyUser(R.string.cannot_delete);
        }
        Log.d(TAG, "Going back");
        super.finish();
    }

    private void notifyUser(int messageResource) {
        Toast.makeText(this, messageResource, Toast.LENGTH_SHORT).show();
    }
}

-class terakhir yang harus dibuat yaitu CameraPreview


package saung.it.video;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";

    private final Camera camera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.camera = camera;
        super.getHolder().addCallback(this);
        // required for API <= 11
        super.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated()");
        // now that we have the surface, we can start the preview
        try {
            this.camera.setPreviewDisplay(holder);
            this.camera.startPreview();
        } catch (IOException e) {
            Log.wtf(TAG, "Failed to start camera preview", e);
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // we will release the camera preview in our activity before this
        // happens
        Log.d(TAG, "surfaceDestroyed()");
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // our activity runs with screenOrientation="landscape" so we don't
        // care about surface changes
        Log.d(TAG, "surfaceChanged()");
    }
}


berikut source xml nya yg pertama video_capture.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/camera_preview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MergeRootFrame" >

    <ImageButton
        android:id="@+id/recordButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:background="#00000000"
        android:contentDescription="@string/record"
        android:onClick="startRecording"
        android:src="@drawable/ic_menu_camera" />

    <ImageButton
        android:id="@+id/stopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:background="#00000000"
        android:contentDescription="@string/stop"
        android:onClick="stopRecording"
        android:src="@drawable/ic_media_stop" />

</FrameLayout>


kedua yaitu video_playback.xml
package saun
  <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <VideoView
        android:id="@+id/video"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:contentDescription="@string/your_video" />

    <ImageButton
        android:id="@+id/backButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|left"
        android:background="#00000000"
        android:contentDescription="@string/back"
        android:onClick="back"
        android:src="@drawable/ic_menu_back" />

    <ImageButton
        android:id="@+id/playButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:background="#00000000"
        android:contentDescription="@string/play"
        android:onClick="play"
        android:src="@drawable/ic_media_play" />

    <ImageButton
        android:id="@+id/stopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:background="#00000000"
        android:contentDescription="@string/stop"
        android:onClick="stop"
        android:src="@drawable/ic_media_stop" />

    <ImageButton
        android:id="@+id/deleteButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:background="#00000000"
        android:contentDescription="@string/delete"
        android:onClick="delete"
        android:src="@drawable/ic_delete" />

</FrameLayout>


terakhir yang sangat penting juga yaitu tentang manifest yang harus dibuat


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.marakana.android.videocapturedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="15" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".VideoCaptureActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VideoPlaybackActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" />
    </application>

</manifest>




nah sekiah tutorial yang saya berikan
mungkin untuk kedepanya saya akan berikan tutorial yang lebih baik lagi
terima kasih

*untuk info aplikasinya bisa berjalan saat di gunakan di hp jadi klo di emulator ga muncul

buat temen" yang pusing liat source code diatas
boleh di download full source code nya :D

Jangan lupa baca yang ini juga



0 comments:

Posting Komentar

PEDOMAN KOMENTAR
Ayo berpartisipasi membangun budaya berkomentar yang baik. Pantang bagi kita memberikan komentar bermuatan menghina atau spam.
Kolom komentar tersedia untuk diskusi, berbagi ide dan pengetahuan. Hargai pembaca lain dengan berbahasa yang baik dalam berekspresi. Setialah pada topik. Jangan menyerang atau menebar kebencian terhadap suku, agama, ras, atau golongan tertentu.

Bangun sharing ilmu dengan berkomentar disini :