简单的录音功能,测试一下代码,直接贴::::
package com.example.testbuttomtoolbar.testbuttomtoolbar;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity {
private Button btnRecord=null;
private Button btnStop=null;
private SurfaceView mSurfaceView=null;
private SurfaceHolder mSurfaceHolder=null;
private MediaRecorder recorder=null;
private File myRecAudioFile=null;
private File dir=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.setKeepScreenOn(true);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
btnRecord=findViewById(R.id.record);
btnStop=findViewById(R.id.stop);
File defaultDir = Environment.getExternalStorageDirectory();
String path = defaultDir.getAbsolutePath()+File.separator+"V"+File.separator;
//创建文件夹存放视频
dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
return;
}
}
}
recorder = new MediaRecorder();
//开始录制视频
btnRecord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recorder();
}
});
//停止录制视频
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
recorder.stop();
recorder.reset();
recorder.release();
recorder=null;
}
});
}
public void recorder() {
try {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/mnt/sdcard/luyin2.3gp");
recorder.prepare();
recorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}