下面列出了android.media.MediaRecorder#setOutputFormat ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void startRecording(View view) throws IOException {
startButton.setEnabled(false);
stopButton.setEnabled(true);
File sampleDir = Environment.getExternalStorageDirectory();
try {
audiofile = File.createTempFile("sound", ".3gp", sampleDir);
} catch (IOException e) {
Log.e(TAG, "sdcard access error");
return;
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
recorder.prepare();
recorder.start();
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "Couldn't prepare and start MediaRecorder");
}
mRecorder.start();
}
private void init() {
//如果文件夹不创建的话那么执行到recorder.prepare()就会报错
File dir = new File(audioPath);
if (!dir.exists()) {
dir.mkdirs();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setMaxDuration(MAX_LENGTH);
recorder.setOutputFile(audioFileName);
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
LogUtils.e("MediaRecorder prepare()报错");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
File path = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/recorder/");
path.mkdirs();
audioFile = File.createTempFile(
"recording_" + new Date().getTime(), ".3gp", path);
recorder.setOutputFile(audioFile.getAbsolutePath());
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void initRecorder()
{
audioRecorder = new MediaRecorder();
audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
audioRecorder.setAudioEncodingBitRate(128000);
audioRecorder.setAudioSamplingRate(44100);
audioRecorder.setOutputFile(recordingPath);
audioRecorder.setOnInfoListener(new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mediaRecorder, int i, int i1)
{
stopRecording();
}
});
}
protected void initRecorder()
{
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setVideoEncodingBitRate(100000000);
mediaRecorder.setVideoFrameRate(30);
mediaRecorder.setVideoSize(videoSize.getWidth(),videoSize.getHeight());
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioEncodingBitRate(128000);
mediaRecorder.setAudioSamplingRate(44100);
mediaRecorder.setOutputFile(recordedPath);
}
/**
* 動画撮影のための準備を行います.
*
* @throws IOException 動画撮影の準備に失敗した場合に発生
*/
public synchronized void setUpMediaRecorder(File outputFile) throws IOException {
if (DEBUG) {
Log.e(TAG, "Set up MediaRecorder");
Log.e(TAG, " VideoSize: " + mSettings.getWidth() + "x" + mSettings.getHeight());
Log.e(TAG, " BitRate: " + mSettings.getBitRate());
Log.e(TAG, " FrameRate: " + mSettings.getFrameRate());
Log.e(TAG, " OutputFile: " + outputFile.getAbsolutePath());
}
int rotation = getDisplayRotation();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setOutputFile(outputFile.getAbsolutePath());
mMediaRecorder.setVideoEncodingBitRate(mSettings.getBitRate());
mMediaRecorder.setVideoFrameRate(mSettings.getFrameRate());
mMediaRecorder.setVideoSize(mSettings.getWidth(), mSettings.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mMediaRecorder.setOrientationHint(ORIENTATIONS[mSettings.getSensorOrientation()].get(rotation));
mMediaRecorder.setOnInfoListener(mOnInfoListener);
mMediaRecorder.setOnErrorListener(mOnErrorListener);
mMediaRecorder.prepare();
}
@Override
public void initRecorder(Camera camera, int cameraId, Surface surface, String filePath)
{
mMediaRecorder = new MediaRecorder();
mMediaRecorder.reset();
if (camera != null)
mMediaRecorder.setCamera(camera);
mMediaRecorder.setOnErrorListener(this);
mMediaRecorder.setPreviewDisplay(surface);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//视频源
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频源
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//视频输出格式 也可设为3gp等其他格式
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//音频格式
mMediaRecorder.setVideoSize(640, 480);//设置分辨率,市面上大多数都支持640*480
// mediaRecorder.setVideoFrameRate(25);//设置每秒帧数 这个设置有可能会出问题,有的手机不支持这种帧率就会录制失败,这里使用默认的帧率,当然视频的大小肯定会受影响
//这里设置可以调整清晰度
mMediaRecorder.setVideoEncodingBitRate(2 * 1024 * 512);
if (cameraId == Camera.CameraInfo.CAMERA_FACING_BACK)
mMediaRecorder.setOrientationHint(90);
else
mMediaRecorder.setOrientationHint(270);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);//视频录制格式
mMediaRecorder.setOutputFile(filePath);
}
public void startAudioRecording() {
AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (am.getMode() == AudioManager.MODE_NORMAL) {
mediaRecorder = new MediaRecorder();
String fileName = UUID.randomUUID().toString().substring(0, 8) + ".m4a";
outputFilePath = new File(context.getFilesDir(), fileName);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//maybe we can modify these in the future, or allow people to tweak them
mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioEncodingBitRate(22050);
mediaRecorder.setAudioSamplingRate(64000);
mediaRecorder.setOutputFile(outputFilePath.getAbsolutePath());
try {
isAudioRecording = true;
mediaRecorder.prepare();
mediaRecorder.start();
if (getVisualizerView() != null) {
startLevelListener();
}
} catch (Exception e) {
Log.e(LOG_TAG, "couldn't start audio", e);
}
}
}
@Override
public void onRecordStart() {
Log.d(TAG, "onRecordStart");
try {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setOutputFile(new File(Environment.getExternalStorageDirectory(), "audio.amr").getAbsolutePath());
mMediaRecorder.prepare();
mMediaRecorder.start();
mIsRecording = true;
mHandler.post(new Runnable() {
@Override
public void run() {
float radius = (float) Math.log10(Math.max(1, mMediaRecorder.getMaxAmplitude() - 500)) * ScreenUtils.dp2px(MainActivity.this, 20);
mTextView.setText(String.valueOf(radius));
mVoiceView.animateRadius(radius);
if (mIsRecording) {
mHandler.postDelayed(this, 50);
}
}
});
} catch (IOException e) {
Toast.makeText(this, "MediaRecorder prepare failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public void recordVideo(VideoStartCallback videoStartCallback, VideoStopCallback videoStopCallback, VideoErrorCallback videoErrorCallback) {
try {
this.videoStartCallback = videoStartCallback;
this.videoStopCallback = videoStopCallback;
this.videoErrorCallback = videoErrorCallback;
if (mCameraDevice == null || !mTextureView.isAvailable() || mPreviewSize == null) {
this.videoErrorCallback.onVideoError("Camera not ready.");
return;
}
videoFile = Environment.getExternalStorageDirectory() + "/" + formatter.format(new Date()) + ".mp4";
mMediaRecorder = new MediaRecorder();
//mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setOutputFile(videoFile);
mMediaRecorder.setVideoEncodingBitRate(10000000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
//mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
if (swappedDimensions) {
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(mDisplayOrientation));
} else {
mMediaRecorder.setOrientationHint(ORIENTATIONS.get(mDisplayOrientation));
}
mMediaRecorder.prepare();
closePreviewSession();
createCameraRecordSession();
} catch (IOException ex) {
Log.d(TAG, "Video Recording error"+ex.getMessage());
}
}
public void onRecordClick(View v) {
if (!mRecording) {
File f = new File(getExternalFilesDir(null), "recording.mp4");
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(f.getAbsolutePath());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC_ELD);
mRecorder.setAudioSamplingRate(48000);
mRecorder.setAudioEncodingBitRate(96000);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(TAG, "unable to prepare MediaRecorder");
mRecorder = null;
return;
}
mRecorder.start();
mRecording = true;
setState(STATE_RECORDING);
} else {
mRecorder.stop();
mRecorder.release();
mRecording = false;
setState(STATE_IDLE);
}
}
protected void initRecorder()
{
recordingTimer = null;
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioEncodingBitRate(128000);
mediaRecorder.setAudioSamplingRate(44100);
mediaRecorder.setOutputFile(recordedPath);
}
private void startRecording() {
releaseRecorder();
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecordFileOutput = getAudioFilename();
//TODO: check disk space left?
mRecorder.setOutputFile(mRecordFileOutput.getPath());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch(IOException e) {
releaseRecorder();
//TODO: show popup for failure?
Log.e(TAG, e.toString());
return;
}
mRecorder.start();
mIsRecording = true;
//UI update
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
filenameTxt.setText(mRecordFileOutput.getName());
imageMic.setImageDrawable(drawable_mic_on);
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void startRecord() {
mediaRecorder = new MediaRecorder();
mediaRecorder.reset();
mCamera.unlock();
// 设置录制视频源为Camera(相机)
mediaRecorder.setCamera(mCamera);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
// 设置录制的视频编码h263 h264
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错
mediaRecorder.setVideoSize(width, height);
// 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错
if (SELECTED_CAMERA == CAMERA_FRONT_POSITION) {
mediaRecorder.setOrientationHint(270);
} else {
mediaRecorder.setOrientationHint(90);
}
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setVideoEncodingBitRate(5 * 1024 * 1024);
mediaRecorder.setVideoFrameRate(20);
mediaRecorder.setPreviewDisplay(mHolder.getSurface());
// 设置视频文件输出的路径
mediaRecorder.setOutputFile("/sdcard/love.mp4");
try {
//准备录制
mediaRecorder.prepare();
// 开始录制
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* record voice
*/
public void prepareAudio() {
File dir = FileUtil.newContactFile(FileUtil.FileType.VOICE);
if (dir == null) {
return;
}
if (!dir.exists()) {
dir.mkdirs();
}
recordPath = generateAudioName();
mediaRecorder = new MediaRecorder();
try {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFile(recordPath);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
//When you enter the chat interface, Home key to exit the voice off
e.printStackTrace();
recordListener.startError();
mediaRecorder = null;
return;
}
recordTimer.start();
if (recordListener != null) {
recordListener.wellPrepared();
}
}
public void startAudioRecording ()
{
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO);
if (permissionCheck ==PackageManager.PERMISSION_DENIED)
{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
Snackbar.make(mConvoView.getHistoryView(), R.string.grant_perms, Snackbar.LENGTH_LONG).show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_AUDIO);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
else {
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (am.getMode() == AudioManager.MODE_NORMAL) {
mMediaRecorder = new MediaRecorder();
String fileName = UUID.randomUUID().toString().substring(0, 8) + ".m4a";
mAudioFilePath = new File(getFilesDir(), fileName);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//maybe we can modify these in the future, or allow people to tweak them
mMediaRecorder.setAudioChannels(1);
mMediaRecorder.setAudioEncodingBitRate(22050);
mMediaRecorder.setAudioSamplingRate(64000);
mMediaRecorder.setOutputFile(mAudioFilePath.getAbsolutePath());
try {
mIsAudioRecording = true;
mMediaRecorder.prepare();
mMediaRecorder.start();
} catch (Exception e) {
Log.e(LOG_TAG, "couldn't start audio", e);
}
}
}
}
private boolean prepareMediaRecorder() {
// 默认使用最高质量拍摄
CamcorderProfile profile =
CamcorderProfile.
get(Integer.valueOf((String) mConfig.getCurrentCameraId()), CamcorderProfile.QUALITY_720P);
Size previewSize = chooseOptimalSize();
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(profile.fileFormat);
mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
// mMediaRecorder.setVideoSize(mAspectRatio.getX(), mAspectRatio.getY());
// mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
mMediaRecorder.setVideoSize(previewSize.getWidth(), previewSize.getHeight());
@SuppressWarnings("ConstantConditions")
int sensorOrientation = mCameraCharacteristics.get(
CameraCharacteristics.SENSOR_ORIENTATION);
int rotation = (sensorOrientation +
mDisplayOrientation * (mConfig.getCurrentFacing() == Constants.CAMERA_FACING_FRONT ? 1 : -1) +
360) % 360;
mMediaRecorder.setOrientationHint(rotation);
mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mMediaRecorder.setVideoEncoder(profile.videoCodec);
mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
mMediaRecorder.setAudioChannels(profile.audioChannels);
mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
mMediaRecorder.setAudioEncoder(profile.audioCodec);
mMediaRecorder.setOutputFile(mConfig.getResultFile().getAbsolutePath());
// 如果针对拍摄的文件大小和拍摄时间有设置的话,也可以在这里设置
try {
mMediaRecorder.prepare();
return true;
} catch (Exception e) {
Log.d(TAG, "prepareMediaRecorder: " + e);
}
// 这个时候出现了错误,应该释放有关资源
releaseVideoRecorder();
return false;
}
@Override
protected void encodeWithMediaRecorder() throws IOException {
// We need a local socket to forward data output by the camera to the packetizer
createSockets();
Log.v(TAG,"Requested audio with "+mQuality.bitRate/1000+"kbps"+" at "+mQuality.samplingRate/1000+"kHz");
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(mAudioSource);
mMediaRecorder.setOutputFormat(mOutputFormat);
mMediaRecorder.setAudioEncoder(mAudioEncoder);
mMediaRecorder.setAudioChannels(1);
mMediaRecorder.setAudioSamplingRate(mQuality.samplingRate);
mMediaRecorder.setAudioEncodingBitRate(mQuality.bitRate);
// We write the output of the camera in a local socket instead of a file !
// This one little trick makes streaming feasible quiet simply: data from the camera
// can then be manipulated at the other end of the socket
FileDescriptor fd = null;
if (sPipeApi == PIPE_API_PFD) {
fd = mParcelWrite.getFileDescriptor();
} else {
fd = mSender.getFileDescriptor();
}
mMediaRecorder.setOutputFile(fd);
mMediaRecorder.setOutputFile(fd);
mMediaRecorder.prepare();
mMediaRecorder.start();
InputStream is = null;
if (sPipeApi == PIPE_API_PFD) {
is = new ParcelFileDescriptor.AutoCloseInputStream(mParcelRead);
} else {
try {
// mReceiver.getInputStream contains the data from the camera
is = mReceiver.getInputStream();
} catch (IOException e) {
stop();
throw new IOException("Something happened with the local sockets :/ Start failed !");
}
}
// the mPacketizer encapsulates this stream in an RTP stream and send it over the network
mPacketizer.setInputStream(is);
mPacketizer.start();
mStreaming = true;
}