实现效果截图:
安卓使用MediaRecorder实现录制视频,设置视频和音频的来源,保存格式,录制质量和速率,并保存到内存中,
用SurfaceView展示画面。
Activity代码:
package com.example.android_vedioplayer_camera_recorder; import android.media.MediaRecorder; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.SurfaceView; import android.view.View; import java.io.IOException; /** * Created by Administrator on 2017/2/22. */ public class RecorderActivity extends AppCompatActivity { private SurfaceView sv_media_recoder_surface; private MediaRecorder mediaRecorder; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recorder); 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/LuoMei_"+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(); } }
layout.xml代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <SurfaceView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/sv_media_recoder_surface" /> <LinearLayout android:layout_width="match_parent" android:layout_alignParentBottom="true" android:layout_height="wrap_content"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:text="开始" android:onClick="start" android:layout_weight="1" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:text="停止" android:onClick="stop" android:layout_weight="1" /> </LinearLayout> </RelativeLayout>