西安企云基创软件有限公司

android实现拍照、录制视频并上传至服务器

         拍照、录制视频、上传、服务器配置、预览视频等功能,代码如下 :
package cn.itcast.videorecord;
import java.io.File;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements
		DialogInterface.OnClickListener
{
	private static final String TAG = "MainActivity";
	private SurfaceView surfaceView;
	private MediaRecorder mediaRecorder;
	private boolean record;
	private File videoFile;
	private ProgressDialog progressDialog = null;// 上传进度条
	private long videoLenth = 0;
	Thread thread;
	private Camera camera = null;
	private Socket receiver;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Window window = getWindow();// 得到窗口
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 没有标题
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 屏幕高亮
		setContentView(R.layout.main);
		mediaRecorder = new MediaRecorder();
		surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView);
		/* 下面设置Surface不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前 */
		this.surfaceView.getHolder().setType(
				SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		this.surfaceView.getHolder().setFixedSize(800, 600);// 设置分辨率
		ButtonClickListener listener = new ButtonClickListener();//修改这里切换传输
		Button stopButton = (Button) this.findViewById(R.id.stop);
		Button recordButton = (Button) this.findViewById(R.id.record);
		stopButton.setOnClickListener(listener);
		recordButton.setOnClickListener(listener);
		/*
		 * // IP按钮 Button IPButton = (Button) findViewById(R.id.IPbutton);
		 * IPButton.setOnClickListener(new Button.OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub onShowPromptDialog(v); } });
		 */
	}
	/**
	 * 显示对话框的IP
	 */
	public void onShowPromptDialog(View v)
	{
		// inflate需要显示到Dialog里的View对象
		LayoutInflater li = LayoutInflater.from(this);
		View view = li.inflate(R.layout.log, null);
		EditText td = (EditText) view.findViewById(R.id.editText_prompt);
		td.setText("lvjun5555555555");
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("请输入上传主机的IP地址");
		builder.setIcon(R.drawable.ic_launcher);
		// 之前inflate的View 放到dialog中
		
		builder.setView(view);
		
		builder.setPositiveButton("确定", this);
		builder.setNegativeButton("取消", this);
		builder.create().show();
	}
	/**
	 * 实现Dialog的回调方法
	 */
	@Override
	public void onClick(DialogInterface dialog, int which)
	{
		// TODO Auto-generated method stub
		if (which == Dialog.BUTTON_POSITIVE)
		{
			AlertDialog ad = (AlertDialog) dialog;
			EditText t = (EditText) ad.findViewById(R.id.editText_prompt);
			String ip = t.getText().toString();
			StreamTool.createFile(ip);
			System.out.println("修改成功");
			Toast.makeText(this, t.getText().toString(), Toast.LENGTH_LONG)
					.show();
		}
	}
	/**
	 * 当activity摧毁时调用
	 */
	@Override
	protected void onDestroy()
	{
		mediaRecorder.release();
		super.onDestroy();
	}
	/**
	 * 保存到本地在上传
	 * 
	 * @author Administrator 吕俊
	 */
	private final class ButtonClickListener implements View.OnClickListener
	{
		@Override
		public void onClick(View v)
		{
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED))
			{
				Toast.makeText(MainActivity.this, R.string.sdcarderror, 1)
						.show();
				return;
			}
			try
			{
				switch (v.getId())
				{
					case R.id.record:
						mediaRecorder.reset();
						mediaRecorder
								.setVideoSource(MediaRecorder.VideoSource.CAMERA); // 从照相机采集视频
						mediaRecorder
								.setAudioSource(MediaRecorder.AudioSource.MIC);
						mediaRecorder
								.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
						mediaRecorder.setVideoSize(480, 320);
						mediaRecorder.setVideoFrameRate(3); // 每秒3帧
						mediaRecorder
								.setVideoEncoder(MediaRecorder.VideoEncoder.H263); // 设置视频编码方式
						mediaRecorder
								.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
						videoFile = new File(
								Environment.getExternalStorageDirectory(),
								System.currentTimeMillis()   ".MP4");
						mediaRecorder.setPreviewDisplay(surfaceView.getHolder()
								.getSurface());
						mediaRecorder
								.setOutputFile(videoFile.getAbsolutePath());
						mediaRecorder.prepare();// 预期准备
						mediaRecorder.start();// 开始刻录
						record = true;
						break;
					case R.id.stop:
						if (record)
						{
							System.out.println(videoFile);
							mediaRecorder.stop();
							record = false;
							progressDialog = new ProgressDialog(
									MainActivity.this);
							progressDialog
									.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
							progressDialog.setIcon(R.drawable.camera);
							progressDialog.setTitle(R.string.upload);
							progressDialog.setButton("取消上传",
									new DialogInterface.OnClickListener()
									{
										@Override
										public void onClick(
												DialogInterface dialog,
												int which)
										{
											// TODO Auto-generated method stub
											thread.interrupt();
										}
									});
							progressDialog.show();
							thread = new Thread(new UploadTask());
							thread.start();
						}
						break;
				}
			} catch (Exception e)
			{
				Toast.makeText(MainActivity.this, R.string.error, 1).show();
				Log.e(TAG, e.toString());
			}
		}
	}
	/**
	 * 实时上传到PC端(边录边传)
	 * 
	 * @author Administrator 吕俊
	 */
	private final class ButtonClickListener1 implements View.OnClickListener
	{
		@Override
		public void onClick(View v)
		{
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED))
			{
				Toast.makeText(MainActivity.this, R.string.sdcarderror, 1)
						.show();
				return;
			}
			try
			{
				switch (v.getId())
				{
					case R.id.record:
						mediaRecorder.reset();
						mediaRecorder
								.setVideoSource(MediaRecorder.VideoSource.CAMERA); // 从照相机采集视频
						//mediaRecorder
								//.setAudioSource(MediaRecorder.AudioSource.MIC);
						mediaRecorder
								.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
						mediaRecorder.setVideoSize(480, 320);
						mediaRecorder.setVideoFrameRate(3); // 每秒3帧
						mediaRecorder
								.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); // 设置视频编码方式
						//mediaRecorder
						//		.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
						mediaRecorder.setPreviewDisplay(surfaceView.getHolder()
								.getSurface());
						// 实时上传的代码
						 receiver = new Socket("192.168.1.149", 9999);
						ParcelFileDescriptor pfd = ParcelFileDescriptor
								.fromSocket(receiver);
						mediaRecorder.setOutputFile(pfd.getFileDescriptor());
						mediaRecorder.prepare();// 预期准备
						mediaRecorder.start();// 开始刻录
						record = true;
						break;
					case R.id.stop:
						if (record)
						{
							System.out.println(videoFile);
							mediaRecorder.stop();
							mediaRecorder.release();
							receiver.close();
							record = false;
						}
						break;
				}
			} catch (Exception e)
			{
				Toast.makeText(MainActivity.this, R.string.error, 1).show();
				Log.e(TAG, e.toString());
			}
		}
	}
	/**
	 * 文件上传连接服务器的
	 * 
	 * 
	 * **/
	class UploadTask implements Runnable
	{
		@Override
		public void run()
		{
			try
			{
				videoLenth = videoFile.length();// 得到文件的大小
				progressDialog.setMax((int) videoLenth);// 设置精度条的最大值
				System.out.println("连接之前");
				String ip = StreamTool.readIP();// 从配置文件里读取Ip
				Socket socket = new Socket(ip, 6789);
				OutputStream outStream = socket.getOutputStream();
				System.out.println("连接之后");
				System.out.println(videoFile);
				String head = "Content-Length="   videoFile.length()
						  ";filename="   videoFile.getName()   ";sourceid=\r\n";
				System.out.println(videoFile.getName());
				outStream.write(head.getBytes());
				PushbackInputStream inStream = new PushbackInputStream(
						socket.getInputStream());
				String response = StreamTool.readLine(inStream);
				System.out.println(response);
				String[] items = response.split(";");
				String position = items[1].substring(items[1].indexOf("=")   1);
				RandomAccessFile fileOutStream = new RandomAccessFile(
						videoFile, "r");
				fileOutStream.seek(Integer.valueOf(position));
				byte[] buffer = new byte[1024];
				int len = -1;
				int i = 1;
				while ((len = fileOutStream.read(buffer)) != -1)
				{
					outStream.write(buffer, 0, len);
					// if(i==10) break;
					Log.i("haha", len   "");
					i = i   len;
					progressDialog.setProgress(i);
				}
				fileOutStream.close();
				outStream.close();
				inStream.close();
				socket.close();
			} catch (Exception e)
			{
				System.out.println("报错"   e.getMessage());
				e.printStackTrace();
			} finally
			{
				progressDialog.dismiss();
			}
		}
	}
}

联系电话:13572265258、13324575128
QQ:455075912

服务宗旨

        我们为政府及企事业单位提供从管理咨询、软件定制开发、软件实施以及运营维护的全程、优势、一体化业务生态链服务体系。以业务流程梳理、优化和数据标准化为目标的管理咨询,协助企业提升管理基础。基于SCP智慧云平台的构件组装思想,以创新的“BTO+DIY”模式为客户提供可视化、快速的软件定制开发。我们为企业提供长期的软件系统运营和维护服务,持续地进行软件系统的维护、升级和完善,为客户创造长期的价值和潜在的增长(BTO:客户提需求,软件“按单生产”,量身打造业务系统;DIY:软件DIY,你的系统你做主)。