Android MediaRecorder.prepare() 是做什么的?

What does Android MediaRecorder.prepare() do?

official Android documentation for MediaRecorder.prepare() 说:

Prepares the recorder to begin capturing and encoding data. This method must be called after setting up the desired audio and video sources, encoders, file format, etc., but before start().

具体是做什么的,为什么我们需要在开始捕获媒体数据之前调用它?

此函数 (prepare()) 将创建一个随机访问文件流以从具有指定名称的文件中读取并可选择写入文件。 这是流处理所必需的。除非使用此功能,否则不会启动流进程。 see this doc.

您可能想在这里阅读源代码:MediaRecorder.java:833

代码一瞥:

/**
 * Prepares the recorder to begin capturing and encoding data. This method
 * must be called after setting up the desired audio and video sources,
 * encoders, file format, etc., but before start().
 *
 * @throws IllegalStateException if it is called after
 * start() or before setOutputFormat().
 * @throws IOException if prepare fails otherwise.
 */
public void prepare() throws IllegalStateException, IOException
{
    if (mPath != null) {
        RandomAccessFile file = new RandomAccessFile(mPath, "rws");
        try {
            _setOutputFile(file.getFD(), 0, 0);
        } finally {
            file.close();
        }
    } else if (mFd != null) {
        _setOutputFile(mFd, 0, 0);
    } else {
        throw new IOException("No valid output file");
    }

    _prepare();
}

这里是代码的原生部分:mediarecorder.cpp

status_t MediaRecorder::prepare()
{
    ALOGV("prepare");
    if (mMediaRecorder == NULL) {
        ALOGE("media recorder is not initialized yet");
        return INVALID_OPERATION;
    }
    if (!(mCurrentState & MEDIA_RECORDER_DATASOURCE_CONFIGURED)) {
        ALOGE("prepare called in an invalid state: %d", mCurrentState);
        return INVALID_OPERATION;
    }
    if (mIsAudioSourceSet != mIsAudioEncoderSet) {
        if (mIsAudioSourceSet) {
            ALOGE("audio source is set, but audio encoder is not set");
        } else {  // must not happen, since setAudioEncoder checks this already
            ALOGE("audio encoder is set, but audio source is not set");
        }
        return INVALID_OPERATION;
    }

    if (mIsVideoSourceSet != mIsVideoEncoderSet) {
        if (mIsVideoSourceSet) {
            ALOGE("video source is set, but video encoder is not set");
        } else {  // must not happen, since setVideoEncoder checks this already
            ALOGE("video encoder is set, but video source is not set");
        }
        return INVALID_OPERATION;
    }

    status_t ret = mMediaRecorder->prepare();
    if (OK != ret) {
        ALOGE("prepare failed: %d", ret);
        mCurrentState = MEDIA_RECORDER_ERROR;
        return ret;
    }
    mCurrentState = MEDIA_RECORDER_PREPARED;
    return ret;
}