Android自定义录制视频获取setAudioSource失败

时间:2015-11-11 06:10:14

标签: android

我试图为自己的应用程序录制视频的自定义预览表面视图,此代码是我的测试,但我收到此错误:

setAudioSource failed

我的示例代码:

    try {
        mCamera.stopPreview();
        mCamera.unlock();
        mRecorder = new MediaRecorder();
        mRecorder.setCamera(mCamera);

        mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setVideoSize(176, 144);
        mRecorder.setVideoFrameRate(15);
        mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mRecorder.setMaxDuration(7000); 
        mRecorder.setPreviewDisplay(mHolder.getSurface());
        mRecorder.setOutputFile(mOutputFileName);

        mRecorder.prepare();
        Log.v(TAG, "MediaRecorder initialized");
        mInitBtn.setEnabled(false);
        mStartBtn.setEnabled(true);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

如果您在Android M上运行,则需要在首次运行时请求录制音频的权限。要完成此操作,请询问用户是否可以在应用程序启动时录制音频:

private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 29;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
            MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {
        Log.d("Home", "Already granted access");
        initializeView(v);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("Home", "Permission Granted");
                initializeView(v);
            } else {
                Log.d("Home", "Permission Failed");
                Toast.makeText(getActivity().getBaseContext(), "You must allow permission record audio to your mobile device.", Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        }
        // Add additional cases for other permissions you may have asked for
    }
}

另外,不要忘记将以下内容添加到您的清单中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />