android 視頻拍攝及播放 -开发者知识库

最近公司項目可能需要一個手機錄制視頻,播放並上傳到服務器的功能  這里只做了錄制播放 上傳還沒有實現 先傳這么多啊


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(MediaPlayer mp) {
// 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>

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复