java.lang.IllegalStateException : failed to get surface 错误

标签 java android

我正在尝试创建一个应用程序,使用户能够记录他的智能手机的屏幕。 这是我的起始代码:

   import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity
{

    private static final int CAST_PERMISSION_CODE = 22;
    private DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    private MediaProjection mMediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaRecorder mMediaRecorder;
    private MediaProjectionManager mProjectionManager;

    private Button startButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = (Button) findViewById( R.id.recordButton );

        mMediaRecorder = new MediaRecorder();

        mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);

        getWindowManager().getDefaultDisplay().getMetrics(this.mDisplayMetrics);

        prepareRecording();
        startRecording();
    }

    private void startRecording() {
        // If mMediaProjection is null that means we didn't get a context, lets ask the user
        if (mMediaProjection == null) {
            // This asks for user permissions to capture the screen
            startActivityForResult(mProjectionManager.createScreenCaptureIntent(), CAST_PERMISSION_CODE);
            return;
        }
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }

    private void stopRecording() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
        }
        if (mVirtualDisplay != null) {
            mVirtualDisplay.release();
        }
        if (mMediaProjection != null) {
            mMediaProjection.stop();
        }
        prepareRecording();
    }

    public String getCurSysDate() {
        return new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    }

    private void prepareRecording() {
        try {
            mMediaRecorder.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        final String directory = Environment.getExternalStorageDirectory() + File.separator + "Recordings";
        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, "Failed to get External Storage", Toast.LENGTH_SHORT).show();
            return;
        }
        final File folder = new File(directory);
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdir();
        }
        String filePath;
        if (success) {
            String videoName = ("capture_" + getCurSysDate() + ".mp4");
            filePath = directory + File.separator + videoName;
        } else {
            Toast.makeText(this, "Failed to create Recordings directory", Toast.LENGTH_SHORT).show();
            return;
        }

        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;

        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(width, height);
        mMediaRecorder.setOutputFile(filePath);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != CAST_PERMISSION_CODE) {
            // Where did we get this request from ? -_-
            //Log.w(TAG, "Unknown request code: " + requestCode);
            return;
        }
        if (resultCode != RESULT_OK) {
            Toast.makeText(this, "Screen Cast Permission Denied :(", Toast.LENGTH_SHORT).show();
            return;
        }
        mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
        // TODO Register a callback that will listen onStop and release & prepare the recorder for next recording
        // mMediaProjection.registerCallback(callback, null);
        mVirtualDisplay = getVirtualDisplay();
        mMediaRecorder.start();
    }

    private VirtualDisplay getVirtualDisplay()
    {
        int screenDensity = mDisplayMetrics.densityDpi;
        int width = mDisplayMetrics.widthPixels;
        int height = mDisplayMetrics.heightPixels;

        return mMediaProjection.createVirtualDisplay(this.getClass().getSimpleName(), width, height, screenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
    }

}

在显示一条通知用户有关屏幕捕获功能的消息后,我的应用崩溃了。

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=22, result=-1, data=Intent { (has extras) }} to activity {gr.awm.clrecorder/gr.awm.clrecorder.MainActivity}: java.lang.IllegalStateException: failed to get surface
                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:3974)
                                                                   at android.app.ActivityThread.handleSendResult(ActivityThread.java:4017)
                                                                   at android.app.ActivityThread.access$1400(ActivityThread.java:172)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1471)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                   at android.os.Looper.loop(Looper.java:145)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                Caused by: java.lang.IllegalStateException: failed to get surface
                                                                   at android.media.MediaRecorder.getSurface(Native Method)
                                                                   at gr.awm.clrecorder.MainActivity.getVirtualDisplay(MainActivity.java:148)
                                                                   at gr.awm.clrecorder.MainActivity.onActivityResult(MainActivity.java:135)

有没有办法解决这个问题?任何建议都会有所帮助并深表感谢。 提前致谢

最佳答案

顺便说一句,别介意评论。

我深入研究了文档和您的代码并获得了以下结果。

这是您调用 mMediaRecorder 方法获取表面的顺序。

mMediaRecorder.prepare();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(width, height);
mMediaRecorder.setOutputFile(filePath);

这就是documentation

//Call this method before prepare().
setVideoEncodingBitRate();  //no exception thrown

//Must be called after setVideoSource(). Call this after setOutFormat() but before prepare().
setVideoSize(width, height);  //IllegalStateException if it is called after prepare() or before setOutputFormat() 

//Call this only before setOutputFormat().
setAudioSource(); //IllegalStateException if it is called after setOutputFormat()
setVideoSource(); //IllegalStateException if it is called after setOutputFormat()

//Call this after setOutputFormat() and before prepare().
setVideoEncoder(); //IllegalStateException if it is called before setOutputFormat() or after prepare()
setAudioEncoder(); //IllegalStateException if it is called before setOutputFormat() or after prepare().

//Call this after setAudioSource()/setVideoSource() but before prepare(). 
setOutputFormat(); //IllegalStateException if it is called after prepare() or before setAudioSource()/setVideoSource().

//Call this after setOutputFormat() but before prepare().
setOutputFile(); //IllegalStateException if it is called before setOutputFormat() or after prepare() 

//Must be called after setVideoSource(). Call this after setOutFormat() but before prepare().
setVideoFrameRate(); //IllegalStateException if it is called after prepare() or before setOutputFormat().

//This method must be called after setting up the desired audio and video sources, encoders, file format, etc., but before start()
prepare()  //IllegalStateException if it is called after start() or before setOutputFormat().

因此,为了使 mMediaRecorder 处于正确状态,您必须按以下顺序调用方法:

setAudioSource()

setVideoSource()

setOutputFormat()

setAudioEncoder()

setVideoEncoder()

setVideoSize()

setVideoFrameRate()

setOutputFile()

setVideoEncodingBitRate()

prepare()

start()

我想当我在 setSource 方法之前调用 setEncoder 方法时我也遇到了一个未记录的错误

编辑:我以为我得到了工作代码,但我仍然得到 IllegalStateExceptions,尽管代码是按文档的顺序排列的。

Edit2:我现在开始工作了。可能也不起作用的事情和其他错误消息:

我必须创建一个应用程序可以写入的目录。我无法让外部存储工作,所以我用了 数据目录。但这与 mMediaRecorder 代码无关

此代码有效:

private void prepareRecording() {

    //Deal with FileDescriptor and Directory here        

    //Took audio out because emulator has no mic
    //mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);

    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

    mMediaRecorder.setVideoEncodingBitRate(512 * 1000);

    //mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

    mMediaRecorder.setVideoSize(width, height);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setOutputFile(filePath);

    try {
        mMediaRecorder.prepare();
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    //Field variable to hold surface object
    //Deal with it as you see fit
    surface = mMediaRecorder.getSurface();

注意 虽然上面的代码可以正确创建 MediaRecorder 并写入存储,但是当 mMediaRecorder.stop() 被调用。

关于java.lang.IllegalStateException : failed to get surface 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711723/

相关文章:

java - Hibernate 会处理表 "bait and switch"吗?

Java:随机生成的数字仅出现在给定范围的一小部分中

android - 如何管理 PreferenceFragment 中的分隔符?

android - react-native运行android失败

Android应用程序不保存在mysql数据库中

java - 转换后如何修复丢失的日期时间?

java - Dagger 2 使用不同的 URL 构建多个 Retrofit 实例,以便使用构造函数注入(inject)来访问不同的 API

java - maven POM中artifactId和name的区别

android - 扩展 FrameLayout, subview 将不再显示

Android 10 - 找不到处理 Intent 的 Activity