Cet article est un contrôle pour l'enregistrement de courtes vidéos avec MediaRecorder. Vous pouvez définir l'heure, la taille de l'espace et s'il faut allumer la caméra initialement, etc. pour l'enregistrement vidéo. Ce contrôle est un contrôle combiné et hérite de LinearLayout. Pour éviter les erreurs, l'interface android.media.MediaRecorder.OnErrorListener doit être implémentée.
Petite interface d'enregistrement vidéo
MovieRecorderView.java
importer java.io.File ; importer java.io.IOException ; importer java.util.Timer ; importer java.util.TimerTask ; importer android.content.Context ; importer android.content.res.TypedArray ; importer android.hardware.Camera ;importer android.hardware.Camera.Parameters;importer android.media.MediaRecorder;importer android.media.MediaRecorder.AudioEncoder ; importer android.media.MediaRecorder.AudioSource ; importer android.media.MediaRecorder.OnErrorListener ; importer android.media.MediaRecorder.OutputFormat ; importer android.media.MediaRecorder.VideoEncoder ; importer android.media.MediaRecorder .VideoSource;importation android.util.AttributeSet ; importer android.view.LayoutInflater ; importer android.view.SurfaceHolder ; importer android.view.SurfaceHolder.Callback ; importer android.view.SurfaceView ; importer android.widget.LinearLayout ; importer android.widget.ProgressBar ; importer com.contron.dgyj.R;importer com.contron.dgyj.common.Globals;import com.contron.dgyj.im.ImGlobal;import com.lidroid.xutils.util.LogUtils /** * Contrôle de lecture vidéo* * @author liuyinjun * * @date 2015- 2-5 */classe publique MovieRecorderView étend LinearLayout implémente OnErrorListener { private SurfaceView mSurfaceView private; SurfaceHolder mSurfaceHolder ; private ProgressBar mProgressBar ; private MediaRecorder mMediaRecorder ; private Camera mCamera ; private Timer mTimer ; // Timer private OnRecordFinishListener ; // Interface de rappel d'achèvement de l'enregistrement private int mWidth ; // Largeur de la résolution vidéo private int mHeight ; isOpenCamera booléen privé ;// S'il faut allumer la caméra depuis le début private int mRecordMaxTime; // La durée maximale pour une prise de vue private int mTimeCount; // Décompte du temps private File mVecordFile = null; // File public MovieRecorderView (Context context) { this (context, null; ); } public MovieRecorderView (contexte de contexte, AttributeSet attrs) { this (contexte, attrs, 0 } public); MovieRecorderView (contexte contextuel, AttributeSet attrs, int defStyle) { super (contexte, attrs, defStyle); TypedArray a = context.obtainStyledAttributes (attrs, R.styleable.MovieRecorderView, defStyle, 0); .MovieRecorderView_width, 320);// Par défaut 320 mHeight = a.getInteger(R.styleable.MovieRecorderView_height, 240); // Par défaut 240 isOpenCamera = a.getBoolean(R.styleable.MovieRecorderView_is_open_camera, true); // Par défaut ouvert mRecordMaxTime = a.getInteger(R.styleable. MovieRecorderView_record_max_time, 10);//La valeur par défaut est 10 LayoutInflater.from(context).inflate(R.layout.movie_recorder_view, this); mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview); mProgressBar = (ProgressBar) findViewById(R. identifiant .progressBar); mProgressBar.setMax(mRecordMaxTime);// Définir la quantité maximale de barre de progression mSurfaceHolder = mSurfaceView.getHolder(); mSurfaceHolder.addCallback(new CustomCallBack()); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS(); * @ date 2015-2-5 */ cours privé CustomCallBack implémente Callback { @Override public void surfaceCreated(SurfaceHolderholder) { if (!isOpenCamera) return; try { initCamera(); } catch (IOException e) { // TODO Bloc de capture généré automatiquement e.printStackTrace(); @Override public void surfaceChanged (support SurfaceHolder, format int, largeur int, hauteur int) { } @Override public void surfaceDestroyed(SurfaceHolderholder) { if (!isOpenCamera) return; freeCameraResource(); } } /** * Initialiser la caméra* * @author liuyinjun * @date 2015-2-5 * @throws IOException */ private void initCamera() lance IOException { if (mCamera != null) { freeCameraResource( } try { mCamera = Camera.open(); } catch (Exception e) { e.printStackTrace(); freeCameraResource(); } if (mCamera == null) return; mSurfaceHolder); mCamera.startPreview(); mCamera.unlock( } /** * Réglez la caméra sur un écran vertical * * @author liuyinjun * @date 2015-2-5 */ private void setCameraParams() { if (mCamera != null) { Paramètres params = mCamera.getParameters(); " , "portrait"); mCamera.setParameters(params); } } /** * Libérer les ressources de la caméra* * @author liuyinjun * @date 2015-2-5 */ private void freeCameraResource() { if (mCamera != null) { mCamera.setPreviewCallback(null); mCamera.lock(); mCamera = null; } } private void createRecordDir() { Fichier sampleDir = nouveau Fichier (Environment.getExternalStorageDirectory() + File.separator + "im/video/"); if (!sampleDir.exists()) { sampleDir.mkdirs(); File vecordDir = sampleDir; // Créer un fichier try { mVecordFile = Fichier.createTempFile("enregistrement", ".mp4", vecordDir);//format mp4 LogUtils.i(mVecordFile.getAbsolutePath()); } catch (IOException e) { } } /** * Initialisation* * @author liuyinjun * @date 2015-2-5 * @throws IOException * / private void initRecord() lance IOException { mMediaRecorder = new MediaRecorder(); mMediaRecorder.reset(); if (mCamera != null) mMediaRecorder.setCamera(mCamera); mMediaRecorder.setOnErrorListener(this); Source vidéo mMediaRecorder.setAudioSource(AudioSource.MIC);//Source audio mMediaRecorder.setOutputFormat(OutputFormat.MPEG_4);//Format de sortie vidéo mMediaRecorder.setAudioEncoder(AudioEncoder.AMR_NB);//Format audio mMediaRecorder.setVideoSize(mWidth, mHeight) ;//Définir la résolution : // mMediaRecorder.setVideoFrameRate(16);// J'ai supprimé cela, cela semble inutile mMediaRecorder.setVideoEncodingBitRate(1 * 1024 * 512);// Définissez la fréquence d'image, et ce sera alors clair. ;/ / La sortie est pivotée de 90 degrés, conservant l'enregistrement d'écran vertical mMediaRecorder.setVideoEncoder(VideoEncoder.MPEG_4_SP); // Format d'enregistrement vidéo // mediaRecorder.setMaxDuration(Constant.MAXVEDIOTIME * 1000); mMediaRecorder.prepare(); try { mMediaRecorder.start(); } catch (IllegalStateException e) { e.printStackTrace(); (); } } /** * Démarrer l'enregistrement vidéo* * @author Liuyinjun * @date 2015-2-5 * @param fileName * Emplacement de stockage de la vidéo * @param onRecordFinishListener * Interface de rappel une fois l'heure spécifiée atteinte */ public void record(final OnRecordFinishListener onRecordFinishListener) { this.mOnRecordFinishListener = onRecordFinishListener; createRecordDir(); (! isOpenCamera)//Si la caméra n'est pas allumée, ouvrez initCamera(); initRecord(); mTimeCount = 0; // Réaffecter le compteur de temps mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { // TODO Stub de méthode généré automatiquement mTimeCount++; mProgressBar. setProgress(mTimeCount);//Définir la barre de progression if (mTimeCount == mRecordMaxTime) {// Lorsque l'heure spécifiée est atteinte, arrêtez de tirer stop(); if (mOnRecordFinishListener != null) mOnRecordFinishListener.onRecordFinish(); 0, 1000); catch (IOException e) { e.printStackTrace(); /** * Arrêtez de tirer * * @author liuyinjun * @date 2015-2-5 */ public void stop() { stopRecord(); releaseRecord(); freeCameraResource(); } /** * Arrêter l'enregistrement* * @author liuyinjun * @date 2015-2-5 */ public void stopRecord() { mProgressBar.setProgress(0); mTimer != null) mTimer.cancel(); if (mMediaRecorder != null) { // Il ne plantera pas après le réglage. mMediaRecorder.setOnErrorListener(null); mMediaRecorder.setPreviewDisplay(null); try { mMediaRecorder.stop(); catch (IllegalStateException e) { e.printStackTrace( } catch (RuntimeException e) { e. .printStackTrace (); } catch (Exception e) { e.printStackTrace( } } } /** * Libérer les ressources * * @author liuyinjun * @date 2015-2-5 */ private void releaseRecord() { if (mMediaRecorder != null) { mMediaRecorder.setOnErrorListener(null try { mMediaRecorder.release()); ; } catch (IllegalStateException e) { e.printStackTrace( } catch (Exception e) { e.printStackTrace(); } } mMediaRecorder = null; } public int getTimeCount() { return mTimeCount; } /** * @return the mVecordFile */ public File getmVecordFile() { return mVecordFile } /** * Rappel de fin d'enregistrement; Interface * * @auteur liuyinjun * * @date 2015-2-5 */ interface publique OnRecordFinishListener { public void onRecordFinish(); } @Override public void onError(MediaRecorder mr, int quoi, int extra) { try { if (mr != null) mr.reset( } catch (IllegalStateException e) { e.printStackTrace (); } catch (Exception 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>
Ce qui précède représente l’intégralité du contenu de cet article, j’espère que vous l’aimerez tous.