MediaRecorder以1秒的延迟启动。我如何摆脱沉默?

时间:2011-10-04 04:31:06

标签: android mediarecorder

我正在尝试在服务中使用MediaRecorder来录制声音。但它在开始时会产生1秒的延迟(静音)。如何摆脱这个?我尝试使用RehearsalAudioRecorder仍然没有运气。如果有人在解决此问题之前请提出建议。

开始

Intent serviceIntent = new Intent();
            serviceIntent.setAction("com.soundrecoder.RecorderService");
            serviceIntent.putExtra("audioFile", path);
            serviceIntent.putExtra("state", true);
            startService(serviceIntent);

停止

Intent serviceIntent = new Intent();
            serviceIntent.setAction("com.soundrecoder.RecorderService");
            serviceIntent.putExtra("state", false);
            startService(serviceIntent);

RecorderService.java文件

public class RecorderService extends Service
{
    private static final String TAG = null;
    private static MediaRecorder mRecorder;

    public void onCreate() {};

    public void onStart(Intent intent, int startId)
    {
        boolean isStart = intent.getBooleanExtra("state", false);

        if (isStart) {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(intent.getStringExtra("audioFile"));

            try {
                mRecorder.prepare();
            } catch (IllegalStateException e) {
                Log.e(TAG,e.getMessage());
            } catch (IOException e) {
                Log.e(TAG,e.getMessage());
            }
            try {
                mRecorder.start();
            }
            catch (IllegalStateException e) {
                Log.e(TAG, e.getMessage());
            }
        }

        else if (!isStart) {
            mRecorder.stop();
            mRecorder.reset();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

我找到了RehearsalAudioRecorder的解决方案

public void onStart(Intent intent, int startId) {
        boolean isStart = intent.getBooleanExtra("state", false);

        if (isStart) {

            acquireWakeLock();

            int i = 0;

            do {
                if (mRecorder != null)
                    mRecorder.release();

                 mRecorder = new RehearsalAudioRecorder(false, 0, 0, 0, 0);

            } while ((++i < 44100)
                    & !(mRecorder.getState() == RehearsalAudioRecorder.State.INITIALIZING));

            mRecorder.setOutputFile(intent.getStringExtra("audioFile"));
            mRecorder.prepare();
            mRecorder.start();

        } else if (!isStart) {

            if(mRecorder != null) {
                mRecorder.stop();
                mRecorder.release();
                mRecorder = null;
            }

            releaseWakeLock();

        }
    }