最近公司项目可能需要一个手机录制视频,播放并上传到服务器的功能 这里只做了录制播放 上传还没有实现 先传这么多啊
mainactivity类里
package com.example.videostart;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
@SuppressLint("NewApi") public class MainActivity extends Activity implements SurfaceHolder.Callback,
OnInfoListener,
OnErrorListener {
private SurfaceView mSurfaceview;
private Button mBtnStartStop;
private Button mBtnPlay;
private TextView mTextView;
private boolean mIsPlay = false; //是否正在播放
private boolean mStartedFlg = false; //是否正在录像
private MediaPlayer mediaPlayer; //多媒体播放器
private int text = 0;
private MediaRecorder mRecorder; //多媒体录音
private Camera mCamera; //相机
private String path; //视频保存路径
private SurfaceHolder mSurfaceHolder;
private android.os.Handler handler = new android.os.Handler(); //android.os 是一个移动设备,智能手机和平板电脑的操作系统
private Runnable runnable = new Runnable() {@Override public void run() {
text++;
mTextView.setText(text + "s");
handler.postDelayed(this, 1000); //休眠1秒
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 设置全屏
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.activity_main);
intView();
SurfaceHolder holder = mSurfaceview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //缓冲区
holder.setFixedSize(176, 144);
holder.setKeepScreenOn(true);
}
private void intView() {
mSurfaceview = (SurfaceView) findViewById(R.id.surfaceview);
mBtnStartStop = (Button) findViewById(R.id.btnStartStop);
mBtnPlay = (Button) findViewById(R.id.btnPlayVideo);
mTextView = (TextView) findViewById(R.id.text);
}
@Override public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
mSurfaceHolder = holder;
}
@Override public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceview = null;
mSurfaceHolder = null;
handler.removeCallbacks(runnable);
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public void onStartStopPlay(View view) {
switch (view.getId()) {
case R.id.btnStartStop:
if (mIsPlay) {
if (mediaPlayer != null) {
mIsPlay = false;
mediaPlayer.stop(); //停止媒体播放器
mediaPlayer.reset(); //重置媒体播放器
mediaPlayer.release(); //释放资源
mediaPlayer = null;
}
}
//如果正在录像
if (!mStartedFlg) {
handler.postDelayed(runnable, 1000);
if (mRecorder == null) {
mRecorder = new MediaRecorder();
}
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
mCamera.startPreview();
if (mCamera != null) {
mCamera.setDisplayOrientation(90);
mCamera.unlock();
mRecorder.setCamera(mCamera);
}
// 这两项需要放在setOutputFormat之前,设置音频和视频的来源
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //音频来源
mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); //相机
// Set output file format
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); //输出格式 mp4
// 这两项需要放在setOutputFormat之后 设置编码器
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); //音频编码格式
mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); //视频编码格式
// mRecorder.setVideoSize(640, 480);//视频分辨率
// mRecorder.setVideoFrameRate(30);//帧速率
mRecorder.setVideoEncodingBitRate(5 * 1024 * 1024); //视频清晰度
mRecorder.setOrientationHint(90); //输出视频播放的方向提示
//设置记录会话的最大持续时间(毫秒)
mRecorder.setMaxDuration(30 * 1000);
mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); //预览显示的控件
path = getSDPath();
if (path != null) {
File dir = new File(path + "/recordtest");
if (!dir.exists()) { //如果不存在这个文件,则创建。
dir.mkdir();
}
path = dir + "/" + getDate() + ".mp4";
// path = "recordtest"+ "/"+ "rocd.mp4";
try {
mRecorder.setOutputFile(path); //输出文件路径
Log.i("path路径", path.toString());
mRecorder.prepare(); //准备
Log.i("prepare", "准备走到了");
mRecorder.setOnInfoListener(this);
mRecorder.setOnErrorListener(this);
Log.i("start", "下面是开始");
Toast.makeText(MainActivity.this, "下面是开始", Toast.LENGTH_SHORT).show();
mRecorder.start(); //开始
} catch(IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("开始的tag", e.toString());
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("开始的tag1", e.toString());
}
mStartedFlg = true; //录像开始
mBtnStartStop.setText("结束录制");
}
} //停止
else {
if (mStartedFlg) {
handler.removeCallbacks(runnable);
try {
mRecorder.stop(); //停止
} catch(Exception e) {
// TODO: handle exception
Log.i("停止的tag", e.toString());
}
mRecorder.reset(); //重置,设置为空闲状态
mRecorder.release(); //释放
mRecorder = null;
mBtnStartStop.setText("开始录制");
text = 0;
//释放相机
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
mStartedFlg = false;
}
break;
case R.id.btnPlayVideo:
if (mBtnPlay.getText().toString().trim().equals("播放")) {
if (mStartedFlg) {
Toast.makeText(MainActivity.this, "正在录制,请结束录制再播放", Toast.LENGTH_SHORT).show();
} else {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
if (path == null) {
Toast.makeText(MainActivity.this, "暂无视频资源", Toast.LENGTH_SHORT).show();
} else {
Uri uri = Uri.parse(path);
mediaPlayer = MediaPlayer.create(MainActivity.this, uri);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(mSurfaceHolder); //设置显示的控件
try {
mediaPlayer.prepare();
} catch(Exception e) {
e.printStackTrace();
}
mediaPlayer.start();
mBtnPlay.setText("暂停");
mIsPlay = true;
//监听播放器是否播放结束
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {@Override public void onCompletion(MediaPlayermp{
// mImageView.setVisibility(View.VISIBLE);
mBtnPlay.setText("播放");
mediaPlayer.reset();
mediaPlayer.release();
Toast.makeText(MainActivity.this, "播放完毕", Toast.LENGTH_SHORT).show();
mIsPlay = false; //播放完毕后改回状态
}
});
}
}
} else if (mBtnPlay.getText().toString().trim().equals("继续")) {
mediaPlayer.start();
mBtnPlay.setText("暂停");
mIsPlay = true;
//监听播放器是否播放结束
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {@Override public void onCompletion(MediaPlayer mp) {
// mImageView.setVisibility(View.VISIBLE);
mBtnPlay.setText("播放");
mediaPlayer.reset();
mediaPlayer.release();
Toast.makeText(MainActivity.this, "播放完毕", Toast.LENGTH_SHORT).show();
mIsPlay = false; //播放完毕后改回状态
}
});
} else {
if (mIsPlay) {
mediaPlayer.pause();
mBtnPlay.setText("继续");
mIsPlay = false;
}
}
break;
}
}
//获取系统时间 视频保存的时间
public static String getDate() {
Calendar mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int month = mCalendar.get(Calendar.MONTH);
int day = mCalendar.get(Calendar.DATE);
int hour = mCalendar.get(Calendar.HOUR);
int minute = mCalendar.get(Calendar.MINUTE);
int second = mCalendar.get(Calendar.SECOND);
String date = "" + year + (month + 1) + day + hour + minute + second;
Log.d("date", "date:" + date);
return date;
}
//获取SD卡路径
public String getSDPath() {
File sdDir = null;
// 判断SD卡是否存在
boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (sdCardExist) {
sdDir = Environment.getExternalStorageDirectory(); //获取根目录
return sdDir.toString();
}
return null;
}
@Override public void onError(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
// mRecorder = mr;
}
@Override public void onInfo(MediaRecorder mr, int what, int extra) {
// TODO Auto-generated method stub
// mRecorder = mr;
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SurfaceView
android:id="@+id/surfaceview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp" />
<Button
android:id="@+id/btnStartStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="开始录制"
android:onClick="onStartStopPlay" />
<Button
android:id="@+id/btnPlayVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@id/btnStartStop"
android:onClick="onStartStopPlay"
android:text="播放" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="12dp"
android:layout_marginLeft="20dp"
android:text="0"
android:textSize="25sp" />
</RelativeLayout>