Este artigo é um controle para gravar vídeos curtos com MediaRecorder. Você pode definir a hora, o tamanho do espaço e se deseja ligar a câmera inicialmente, etc. Este controle é um controle de combinação e herda de LinearLayout. Para evitar erros, a interface android.media.MediaRecorder.OnErrorListener precisa ser implementada.
Interface de gravação de vídeo pequena
MovieRecorderView.java
importar java.io.File;importar java.io.IOException;importar java.util.Timer;importar java.util.TimerTask;importar android.content.Context;importar android.content.res.TypedArray;importar android.hardware.Camera ;importar android.hardware.Camera.Parameters;importar android.media.MediaRecorder;importar android.media.MediaRecorder.AudioEncoder;importar android.media.MediaRecorder.AudioSource;importar android.media.MediaRecorder.OnErrorListener;importar android.media.MediaRecorder.OutputFormat;importar android.media.MediaRecorder.VideoEncoder;importar android.media.MediaRecorder .VideoSource;importar android.util.AttributeSet;importar android.view.LayoutInflater;importar android.view.SurfaceHolder;importar android.view.SurfaceHolder.Callback;importar android.view.SurfaceView;importar android.widget.LinearLayout;importar android.widget.ProgressBar; importar com.controle.dgyj.R;importar com.contron.dgyj.common.Globals;importar com.controln.dgyj.im.ImGlobal;importar com.lidroid.xutils.util.LogUtils; /** * Controle de reprodução de vídeo* * @autor liuyinjun * * @data 2015- 2-5 */classe pública MovieRecorderView estende LinearLayout implementa OnErrorListener { private SurfaceView mSurfaceView private; SurfaceHolder mSurfaceHolder; private ProgressBar mProgressBar; // interface de retorno de chamada de conclusão private int mWidth; booleano privado isOpenCamera;// Se deve ligar a câmera desde o início private int mRecordMaxTime; // O tempo máximo para uma filmagem private int mTimeCount; // Contagem de tempo private File mVecordFile = null; ); } public MovieRecorderView(Context context, AttributeSet attrs) { this(context, attrs, 0 } public); MovieRecorderView (Context context, AttributeSet attrs, int defStyle) { super (context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes (attrs, R.styleable.MovieRecorderView, defStyle, 0); .MovieRecorderView_width, 320);// Padrão 320 mHeight = a.getInteger(R.styleable.MovieRecorderView_height, 240); // Padrão 240 isOpenCamera = a.getBoolean(R.styleable.MovieRecorderView_is_open_camera, true); MovieRecorderView_record_max_time, 10);//O padrão é 10 LayoutInflater.from(context).inflate(R.layout.movie_recorder_view, this); mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview); id.progressBar);mProgressBar.setMax(mRecordMaxTime);// Defina a quantidade máxima de barra de progresso mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(new CustomCallBack()); * @ data 2015-2-5 */ aula particular CustomCallBack implementa Callback { @Override public void surfaceCreated(SurfaceHolderholder) { if (!isOpenCamera) return; try { initCamera(); @Override public void surfaceChanged(SurfaceHolder titular, formato int, largura int, altura int) { } @Override public void surfaceDestroyed(SurfaceHolder titular) { if (!isOpenCamera) return; freeCameraResource(); lança IOException { if (mCamera! = null) { freeCameraResource(); mCamera = Camera.open(); catch (Exceção e) { e.printStackTrace(); freeCameraResource(); mSurfaceHolder); mCamera.startPreview(); Defina a câmera para tela vertical * * @author liuyinjun * @date 2015-2-5 */ private void setCameraParams() { if (mCamera != null) { Parameters params = mCamera.getParameters(); " , "retrato"); mCamera.setParameters(params); } } /** * Liberar recursos da câmera* * @author liuyinjun * @data 5/2/2015 */ private void freeCameraResource() { if (mCamera != null) { mCamera.setPreviewCallback(null); mCamera = null; } } private void createRecordDir() { Arquivo sampleDir = novo File(Environment.getExternalStorageDirectory() + File.separator + "im/video/"); if (!sampleDir.exists()) { sampleDir.mkdirs() } File vecordDir = sampleDir; File.createTempFile("gravação", ".mp4", vecordDir);//formato mp4 LogUtils.i(mVecordFile.getAbsolutePath()); } catch (IOException e) { } } /** * Inicialização* * @author liuyinjun * @date 2015-2-5 * @throws IOException * / private void initRecord() lança IOException { mMediaRecorder = novo MediaRecorder(); mMediaRecorder.reset(); Fonte de vídeo mMediaRecorder.setAudioSource(AudioSource.MIC);//Fonte de áudio mMediaRecorder.setOutputFormat(OutputFormat.MPEG_4);//Formato de saída de vídeo mMediaRecorder.setAudioEncoder(AudioEncoder.AMR_NB);//Formato de áudio mMediaRecorder.setVideoSize(mWidth, mHeight) ;//Definir resolução: // mMediaRecorder.setVideoFrameRate(16);// Eu removi isso, parece inútil. mMediaRecorder.setVideoEncodingBitRate(1 * 1024 * 512);// Defina a frequência do quadro e então ficará claro. ;/ / A saída é girada 90 graus, mantendo a gravação de tela vertical. mMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP); // Formato de gravação de vídeo // mediaRecorder.setMaxDuration(Constant.MAXVEDIOTIME * 1000); mMediaRecorder.prepare(); tente { mMediaRecorder.start(); catch (IllegalStateException e) { e.printStackTrace(); (); } } /** * Iniciar a gravação do vídeo* * @author liuyinjun * @date 2015-2-5 * @param fileName * Local de armazenamento do vídeo * @param onRecordFinishListener * Interface de retorno de chamada após o tempo especificado ser atingido */ public void record(final OnRecordFinishListener onRecordFinishListener) { this.mOnRecordFinishListener = onRecordFinishListener; (!isOpenCamera)//Se a câmera não estiver ligada, abra initCamera(); initRecord(); mTimeCount = 0; // Reatribuir o contador de tempo mTimer = new Timer(); setProgress(mTimeCount);//Define a barra de progresso if (mTimeCount == mRecordMaxTime) {// Quando o tempo especificado for atingido, pare de disparar stop(); /** * Pare de atirar * * @author liuyinjun * @date 2015-2-5 */ public void stop() { stopRecord(); releaseRecord(); freeCameraResource() } /** * Parar gravação* * @author liuyinjun * @date 2015-2-5 */ public void stopRecord() { mProgressBar.setProgress(0); mTimer != null) mTimer.cancel(); if (mMediaRecorder != null) { // Ele não travará após a configuração. mMediaRecorder.setOnErrorListener(null); mMediaRecorder.setPreviewDisplay(null); try { mMediaRecorder.stop(); .printStackTrace (); } catch (Exceção e) { e.printStackTrace(); } /** * Liberar recursos * * @author liuyinjun * @date 2015-2-5 */ private void releaseRecord() { if (mMediaRecorder != null) { mMediaRecorder.setOnErrorListener(null); ; } catch (IllegalStateException e) { e.printStackTrace(); e.printStackTrace(); } } mMediaRecorder = null } public int getTimeCount() { return mTimeCount; Interface * * @autor liuyinjun * * @data 2015-2-5 */ interface pública OnRecordFinishListener { public void onRecordFinish (); (); } catch (Exceção e) { e.printStackTrace();
movie_recorder_view.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas .android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_dark" android:orientation="vertical"> <SurfaceView android:id="@+id/surfaceview" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight ="1" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="2dp" /> </LinearLayout>
attrs.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas .android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/background_dark" android:orientation="vertical"> <SurfaceView android:id="@+id/surfaceview" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight ="1" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="2dp" /> </LinearLayout>
O texto acima é todo o conteúdo deste artigo, espero que todos gostem.