Hi
Am new to android development , need to build a POC on video record
and saving it in SDcard. I got some sample in which audio recording
in working but not the video . Could someone help me to solve this
issue . below are the current code where video is not working . i
have commented the video related code as it was throwing some error.
Java Code : VideoTest.java
package com.app.test;
/**
* @author Pankaj
*
*/
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.SimpleCursorAdapter;
/**
* @author Pankaj
*
*/
public class VideoTest extends Activity {
private static final long NO_STORAGE_ERROR = -1L;
private static final long CANNOT_STAT_ERROR = -2L;
private static final long LOW_STORAGE_THRESHOLD = 512L * 1024L;
private static final int STORAGE_STATUS_OK = 0;
private static final int STORAGE_STATUS_LOW = 1;
private static final int STORAGE_STATUS_NONE = 2;
private static final boolean SWITCH_CAMERA = true;
private static final boolean SWITCH_VIDEO = false;
private boolean recording = false;
private ContentValues mCurrentVideoValues;
private int mStorageStatus = STORAGE_STATUS_OK;
private FileDescriptor mCameraVideoFileDescriptor;
private ContentResolver mContentResolver;
private MediaRecorder recorder;
private Context context;
private ContentValues values = new ContentValues(3);
private SurfaceView preview=null;
private SurfaceHolder previewHolder=null;
private Camera camera=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.camera);
preview=(SurfaceView)findViewById(R.id.surface);
// Hide the window title.
previewHolder=preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
} catch (Exception e) {
e.getMessage();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
try {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
if (!recording) {
takePicture();
recording = true;
}else{
stopRecorder();
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
} catch (Exception e) {
e.getMessage();
}
return true;
}
private void stopRecorder() {
try {
if (recorder == null){
return;
}
recorder.stop();
recorder.reset();
recorder.release();
recording = false;
recorder = null;
} catch (Exception e) {
e.getMessage();
}
finally {
if (recorder != null){
recorder.release();
}
}
}
private void takePicture() {
try {
recorder = new MediaRecorder();
String url = createVideoPath();
//Uri base = Uri.parse(url);
//Uri uri = new Uri.Builder().scheme("content").authority
("file").appendPath(url).build();
//camera.unlock();
ContentResolver contentResolver = getContentResolver();
Uri mBase = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(mBase, values);
mCameraVideoFileDescriptor =
contentResolver.openFileDescriptor
(newUri, "rw").getFileDescriptor();
Cursor cursor = getContentResolver().query( newUri, null,
null,
null, null);
String path = "";
while (cursor.moveToNext()) {
path = cursor.getString(1);
}
// could use setPreviewDisplay() to display a preview to
suitable View here
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat
(MediaRecorder.OutputFormat.THREE_GPP);
//recorder.setOutputFile(mCameraVideoFileDescriptor);
recorder.setOutputFile(path);
//recorder.setVideoFrameRate(15);
//recorder.setVideoSize(480, 320);
recorder.setAudioEncoder
(MediaRecorder.AudioEncoder.AMR_NB);
//recorder.setVideoEncoder
(MediaRecorder.VideoEncoder.H263);
//recorder.setPreviewDisplay(previewHolder.getSurface());
try {
//ecorder.setCamera(camera);
recorder.prepare();
} catch (Exception e) {
e.getMessage();
}
try {
recorder.start();
Thread.sleep(100000);
recorder.stop();
recorder.release();
} catch (Exception e) {
e.getMessage();
}
} catch (Exception e) {
e.getMessage();
}
}
SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
camera=Camera.open();
try {
previewHolder = holder;
camera.setPreviewDisplay(previewHolder);
}
catch (Throwable t) {
Log.e("Photographer","Exception in
setPreviewDisplay()", t);
}
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
Camera.Parameters parameters=camera.getParameters();
parameters.setPreviewSize(width, height);
parameters.setPictureFormat(PixelFormat.JPEG);
camera.setParameters(parameters);
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera=null;
}
};
private static final char[] kDigits = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
Camera.PictureCallback photoCallback=new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
JSONObject mLocationJSON = new JSONObject();
try {
mLocationJSON.put("latitude", "lat");
mLocationJSON.put("longitude", "long");
mLocationJSON.put("date", "date");
byte[] imgArray = data;
int length = imgArray.length;
char[] hex = new char[length * 2];
for (int i = 0; i < length; i++) {
int value = (imgArray[i] + 256) % 256;
int highIndex = value >> 4;
int lowIndex = value & 0x0f;
hex[i * 2 + 0] = kDigits[highIndex];
hex[i * 2 + 1] = kDigits[lowIndex];
}
//mLocationJSON.put("photo", new String(hex));
//Photo.postLocationJSON("http://192.168.2.100:8080/Test/test",
mLocationJSON);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}
};
public String createVideoPath() {
try {
long dateTaken = System.currentTimeMillis();
SimpleDateFormat dateFormat = new
SimpleDateFormat("yyyy-MM-dd-
ss");
Date date = new Date(dateTaken);
String filepart = dateFormat.format(date);
String title = filepart;
String displayName = filepart + ".gp3"; // Used when
emailing.
String cameraDirPath =
Environment.getExternalStorageDirectory
().toString() + "/DCIM";
File cameraDir = new File(cameraDirPath);
cameraDir.mkdirs();
String filename = cameraDirPath + "/" + filepart +
".3gp";
values = new ContentValues(7);
values.put(android.provider.MediaStore.Video.Media.TITLE, title);
values.put(android.provider.MediaStore.Video.Media.DISPLAY_NAME,
displayName);
values.put(android.provider.MediaStore.Video.Media.DATE_TAKEN,
dateTaken);
values.put(android.provider.MediaStore.Video.Media.MIME_TYPE,
"video/3gpp");
values.put(android.provider.MediaStore.Video.Media.DATA, filename);
values.put(android.provider.MediaStore.Video.Media.SIZE, 100000);
values.put(android.provider.MediaStore.Video.Media.DATE_ADDED,
dateTaken);
values.put(android.provider.MediaStore.Video.Media.DESCRIPTION,
displayName);
values.put(android.provider.MediaStore.Video.Media.DURATION,
100000);
values.put(android.provider.MediaStore.Video.Media.RESOLUTION,
100);
String mCameraVideoFilename = filename;
new File(mCameraVideoFilename).createNewFile();
Log.v("Video", "Current camera video filename: " +
mCameraVideoFilename);
mCurrentVideoValues = values;
return mCameraVideoFilename;
} catch (Exception e) {
e.getMessage();
}
return "/sdcard/DCIM/test.mp4";
}
private String createName(long dateTaken) {
return DateFormat.format("yyyy-MM-dd kk.mm.ss",
dateTaken).toString
();
}
private int getStorageStatus(boolean mayHaveSd) {
long remaining = mayHaveSd ? getAvailableStorage() :
NO_STORAGE_ERROR;
if (remaining == NO_STORAGE_ERROR) {
return STORAGE_STATUS_NONE;
}
return remaining < LOW_STORAGE_THRESHOLD
? STORAGE_STATUS_LOW
: STORAGE_STATUS_OK;
}
private long getAvailableStorage() {
try {
if (!hasStorage()) {
return NO_STORAGE_ERROR;
} else {
String storageDirectory =
Environment.getExternalStorageDirectory().toString();
StatFs stat = new StatFs(storageDirectory);
return (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
}
} catch (RuntimeException ex) {
// if we can't stat the filesystem then we don't know
how many
// free bytes exist. It might be zero but just leave it
// blank since we really don't know.
return CANNOT_STAT_ERROR;
}
}
public boolean hasStorage() {
return hasStorage(true);
}
public boolean hasStorage(boolean requireWriteAccess) {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
return writable;
} else {
return true;
}
} else if (!requireWriteAccess
&&
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
private boolean checkFsWritable() {
// Create a temporary file to see whether a volume is really
writeable.
// It's important not to put it in the root directory which may
have
a
// limit on the number of files.
String directoryName =
Environment.getExternalStorageDirectory().toString() +
"/DCIM";
File directory = new File(directoryName);
if (!directory.isDirectory()) {
if (!directory.mkdirs()) {
return false;
}
}
File f = new File(directoryName, ".probe");
try {
// Remove stale file if any
if (f.exists()) {
f.delete();
}
if (!f.createNewFile()) {
return false;
}
f.delete();
return true;
} catch (IOException ex) {
return false;
}
}
}
layout>camera.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/
android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SurfaceView android:id="@+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</SurfaceView>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="@+id/play"
android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="Play"
/>
</LinearLayout>
<VideoView android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</LinearLayout>
Mainefes xml
==========
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/
app_name">
<activity android:name=".VideoTest"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="5" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en