java.lang.IllegalStateException: 获取表面失败

8

我正在尝试创建一个应用程序,使用户能够录制他的智能手机屏幕。

这是我的起始代码:

   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)

有解决这个问题的方法吗?任何建议都将是有帮助和深受感激的。谢谢您提前的帮助。

谁调用了onActivityResult?可能是因为您的Activity状态及其字段未在MainActivity接收结果时重新创建。您正在调用mMediaRecorder.getSurface,这似乎是该代码部分唯一会抛出IllegalStateException的方法调用。 - ma cılay
你找到答案了吗?我也遇到了一些设备上的Mediarecorder.getSurface()的IllegalStateException问题。 - Sunil Chaudhary
@SunilChaudhary 我猜你遇到的问题是没有Marshmallow设备.. 你找到解决这个问题的答案了吗? - HB.
3个回答

7

顺便说一下,不用理会这条评论。

我研究了文档和你的代码,得到了以下结果。

这是获取表面的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);

以下是文档中的内容:

//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()

当我在调用setEncoder方法之前调用setSource方法时,我认为我也遇到了未记录错误。

编辑:我以为我获得了可工作的代码,但我仍然会收到IllegalStateExceptions异常,尽管代码按照文档的顺序执行。

编辑2:我现在已经将其工作。还可能不起作用并出现其他错误消息:

我必须创建一个应用程序可以写入的目录。我无法让外部存储器正常工作,因此我使用了数据目录。但这与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()时会导致整个模拟器崩溃。


1
为什么谷歌不创建一个MediaRecorder的Builder,以简化所有这些东西¯_(ツ)_/¯?感谢ma_cilay。 - Sulfkain

2
也许您设置了错误的视频大小或错误的视频源。请确保在执行mediaRecord.prepare()之前已成功执行。
我也遇到了这个问题,检查了上述所有内容后,我解决了这个问题。
"Original Answer" 翻译成 "最初的答案"

0

我刚遇到了同样的问题。 这个问题只会在第一次安装游戏并授权后出现一次, 所以我清除了应用程序的数据(像第一千次那样)来重现错误,但它再也没有发生过。 所以我做的是从存储中删除文件夹, 在你的情况下,文件夹的名称是String directory = "Recordings"

这一次我成功地重现了错误。

为了解决这个问题,我确保在接受“WRITE_EXTERNAL_STORAGE”权限之后并在调用所有MediaRecorder配置之前创建文件夹。

switch (requestCode) {
        case REQUEST_PERMISSIONS: {
            if ((grantResults.length > 0) && (grantResults[0] +
                    grantResults[1]) == PackageManager.PERMISSION_GRANTED) {
                //onToggleScreenShare(mToggleButton);

                File folder = new File(Environment.getExternalStorageDirectory() +
                        File.separator + "textingstories");
                boolean success = true;
                if (!folder.exists()) {
                    success = folder.mkdirs();

                    if (success) {
                        // Do something on success
                        StartRecord();
                    } else {
                        // Do something else on failure
                    }
                }
                else {
                    StartRecord();
                }

对于 Android 10,您可能需要将以下内容添加到清单文件中以确保文件夹被创建:

<manifest ... >
   <application android:requestLegacyExternalStorage="true" ... >
    ...
   </application>
</manifest>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接