用mediarecoder 写一个录音demo
时间: 2024-03-14 22:46:17 浏览: 100
好的,下面是一个使用MediaRecorder录制音频的简单Demo:
1. 在AndroidManifest.xml中添加录音权限:
```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 在布局文件中添加一个按钮,用于开始录制音频:
```xml
<Button
android:id="@+id/start_recording_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Recording" />
```
3. 在Activity中添加如下代码:
```java
private MediaRecorder mediaRecorder;
private String audioFilePath;
private Button startRecordingButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startRecordingButton = findViewById(R.id.start_recording_button);
startRecordingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startRecording();
}
});
}
private void startRecording() {
// 创建音频文件
File audioFile = null;
try {
audioFile = createAudioFile();
} catch (IOException e) {
e.printStackTrace();
}
// 初始化MediaRecorder
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// 开始录制音频
try {
mediaRecorder.prepare();
mediaRecorder.start();
startRecordingButton.setText("Stop Recording");
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
// 停止录制音频
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
startRecordingButton.setText("Start Recording");
}
private File createAudioFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String audioFileName = "AUDIO_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
File audioFile = File.createTempFile(audioFileName, ".3gp", storageDir);
audioFilePath = audioFile.getAbsolutePath();
return audioFile;
}
@Override
protected void onStop() {
super.onStop();
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
```
这个Demo实现了一个简单的录音功能,点击按钮即可开始录制音频,再次点击按钮即可停止录制。录制完成后,音频文件会保存在应用的私有目录中,可以通过audioFilePath获取到音频文件的路径。
阅读全文