gpt4 book ai didi

java - 使用 MediaRecorder 将 View 中的位图编码为视频

转载 作者:行者123 更新时间:2023-11-29 09:27:26 26 4
gpt4 key购买 nike

我一直在尝试将 View 中的位图图像编码为 mp4 视频。我正在使用以 Surface 作为输入的 MediaRecorder 设置。代码在循环中的第二次迭代中失败。貌似 Canvas 没有解锁成功,然后lockCanvas失败,报错。

可能导致此异常的原因是什么?

public class ViewRecorder
{
private View recordView;
private boolean run = true;
private String filename;

public ViewRecorder(View recordView, String filename)
{
this.recordView = recordView;
this.filename = filename;

Thread thread = new Thread(new Task());
thread.start();
}

/*
* Stops the recording
*/
public void Stop()
{
this.run = false;
}

/*
* Encodes a frame every 100 mS
*/
private class Task implements Runnable
{
@Override
public void run()
{
try
{
MediaRecorder mediaRecorder = new MediaRecorder();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoFrameRate(10);
//this.mediaRecorder.setVideoEncodingBitRate(20000);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setOutputFile(filename + ".mp4");

recordView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(recordView.getDrawingCache());
recordView.setDrawingCacheEnabled(false);

mediaRecorder.setVideoSize(bitmap.getWidth(), bitmap.getHeight());

mediaRecorder.prepare();
mediaRecorder.start(); // Recording is now started

while(run)
{
Thread.sleep(100);

recordView.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(recordView.getDrawingCache());
recordView.setDrawingCacheEnabled(false);

Surface surface = mediaRecorder.getSurface();
Canvas canvas = surface.lockCanvas(null);
canvas.drawBitmap(bitmap, 0, 0, new Paint());
surface.unlockCanvasAndPost(canvas);
}

mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

这是异常(exception)情况:

11-21 18:59:35.220 26737-27432/ W/System.err: java.lang.IllegalArgumentException
11-21 18:59:35.220 26737-27432/ W/System.err: at android.view.Surface.nativeLockCanvas(Native Method)
11-21 18:59:35.220 26737-27432/ W/System.err: at android.view.Surface.lockCanvas(Surface.java:322)
11-21 18:59:35.221 26737-27432/ W/System.err: at .ViewRecorder$Task.run(ViewRecorder.java:77)
11-21 18:59:35.221 26737-27432/ W/System.err: at java.lang.Thread.run(Thread.java:762)
11-21 19:00:47.783 26737-26744/ W/art: Suspending all threads took: 35.361ms
11-21 19:01:25.983 26737-26744/ W/art: Suspending all threads took: 22.830ms

最佳答案

不确定您是否仍在寻求解决方案,但我发现了这一点:

移动-Surface surface = mediaRecorder.getSurface();

在循环之外,所以它只被调用一次。第二次调用出错

关于java - 使用 MediaRecorder 将 View 中的位图编码为视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com