表面已发布Media Codec

The surface has been released Media Codec

我正在尝试编写 encoder/decoder 代码以通过 TCP 服务器发送相机并使用 SurfaceView 显示它,当我这样做时 decodec.configure 我有 "The surface has been released"

这是我的代码:

SurfaceHolder.Callback callback1 = new SurfaceHolder.Callback() {

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        Log.d(TAG,"inSurfaceCreated");
        hasActiveHolder = true;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        Log.d(TAG,"inSurfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        Log.d(TAG,"inSurfaceDestroyed");
        hasActiveHolder = false;
    }
};
FrameLayout frameLayout1=findViewById(R.id.frameLayout);
SurfaceView surfaceView = new SurfaceView(this);
SurfaceHolder holder1 = (surfaceView.getHolder());
holder1.addCallback(callback1);
Surface surfaceAffichage = holder1.getSurface();
frameLayout1.addView(surfaceView);
//while(!hasActiveHolder){ }

MediaFormat mediaFormat = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 640, 640);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 1000000);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 20);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
final MediaCodec decodec = MediaCodec.createDecoderByType("video/avc");
decodec.configure(mediaFormat, surfaceAffichage, null, 0);

如果我删除 while 循环的注释,我将永远等待,程序永远不会进入回调 surfaceCreated

有人可以帮助我吗?

您需要在 SurfaceHoler.Callback 的 surfaceCreated 主体中初始化解码器。此回调会在创建底层表面时通知您。

另外:while(!hasActiveHolder){ }不要这样做。如果有回调,请使用它来启动其余的逻辑。 如果您确实需要检查某些事件是否定期发生,请引入等待时间和同步变量访问。