使用MediaRecorder实现录像功能

效果图:
使用MediaRecorder实现录像功能_第1张图片

实现代码:

package com.example.android_27__playvideo_camera_lx;

import android.media.MediaRecorder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;

import java.io.IOException;

public class MediaRecorderActivity extends AppCompatActivity {

    private MediaRecorder mediaRecorder;
    private SurfaceView sv_media_recoder_surface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mediarecorder);
        sv_media_recoder_surface = (SurfaceView) findViewById(R.id.sv_media_recoder_surface);
        //实例化媒体录制器
        mediaRecorder = new MediaRecorder();
    }

    public void start(View view){
        mediaRecorder.reset();
        //设置视频和音频的来源
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

        //设置保存的格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

        //设置编码格式
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        mediaRecorder.setVideoFrameRate(3);

        //设置保存的路径
        mediaRecorder.setOutputFile("mnt/sdcard/mp/G150825_"+System.currentTimeMillis()+".mp4");

        //将画面展示到SurfaceView
        mediaRecorder.setPreviewDisplay(sv_media_recoder_surface.getHolder().getSurface());

        //准备
        try {
            mediaRecorder.prepare();

            mediaRecorder.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void stop(View view){
        mediaRecorder.stop();
    }
}

要加权限:


    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

注意要设置成横屏:

android:screenOrientation="landscape"

你可能感兴趣的:(使用MediaRecorder实现录像功能)