前言
当一个Android开发者玩抖音玩疯了之后,就会绞尽脑汁思考自己是否也能开发出一款相同的APP来呢?
滴,滴滴!
本篇文章将介绍自己总结的短视频录制的相关内容,主要分为三个部分:
- 摄像头内容录制
- 音频录制
- 视频合成
先上效果图
-
录制过程
- 录制结果
1.摄像头内容录制
录制流程大致如上图所示。
渲染关键代码
新建外部纹理
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
mTextureId = GLUtils.createTextureObject(GLES11Ext.GL_TEXTURE_EXTERNAL_OES);
mSurfaceTexture = new SurfaceTexture(mTextureId);
...
}
新建了外部纹理之后,传入 Camera
mCamera.setPreviewTexture(mSurfaceTexture);
mCamera.startPreview();
GLSurfaceView 渲染时,请求 SurfaceTexture 更新,获取最新的内容
@Override
public void onDrawFrame(GL10 gl) {
if (mFilter == null) {
return;
}
float matrix[] = new float[16];
if (mSurfaceTexture != null) {
//请求刷新最新内容
mSurfaceTexture.updateTexImage();
}
mSurfaceTexture.getTransformMatrix(matrix);
if (mFrameListener != null) {
//通知MediaCodec刷新画面
mFrameListener.onFrameAvailable(new VideoFrameData(mFilter,
matrix, mSurfaceTexture.getTimestamp(), mTextureId));
}
mFilter.init();
if (mOldFilter != null) {
mOldFilter.release();
mOldFilter = null;
}
mSurfaceTexture.getTransformMatrix(mMatrix);
//绘制预览内容
mFilter.draw(mTextureId, mMatrix);
}
mFilter 中包含 OpenGL 相关的着色器程序
着色器代码如下:
/**
* 默认代码
*/
private static final String FRAGMENT_CODE =
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"varying vec2 vTextureCoord;\n" +
"uniform samplerExternalOES uTexture;\n" +
"void main() {\n" +
" gl_FragColor = texture2D(uTexture, vTextureCoord);\n" +
"}\n";
/**
* 默认代码
*/
private static final String VERTEX_CODE =
"uniform mat4 uTexMatrix;\n" +
"attribute vec2 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"void main() {\n" +
" gl_Position = vec4(aPosition,0.0,1.0);\n" +
" vTextureCoord = (uTexMatrix * aTextureCoord).xy;\n" +
"}\n";