mediarecorder录制 wav音频文件demo
时间: 2023-07-23 15:33:00 浏览: 200
好的,以下是一个简单的录制 WAV 音频文件的示例代码:
```java
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class AudioRecorder {
private static final String TAG = "AudioRecorder";
private static final int SAMPLE_RATE_IN_HZ = 44100;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord audioRecord;
private boolean isRecording;
public void startRecording() {
int minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT, minBufferSize);
isRecording = true;
audioRecord.startRecording();
new Thread(new Runnable() {
@Override
public void run() {
writeDataToFile();
}
}).start();
}
public void stopRecording() {
isRecording = false;
audioRecord.stop();
audioRecord.release();
}
private void writeDataToFile() {
byte[] buffer = new byte[1024];
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.wav";
File file = new File(filename);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream fos = new FileOutputStream(file);
while (isRecording) {
int read = audioRecord.read(buffer, 0, buffer.length);
fos.write(buffer, 0, read);
}
fos.close();
} catch (IOException e) {
Log.e(TAG, "writeDataToFile: ", e);
}
}
}
```
将上述代码保存到名为 `AudioRecorder.java` 的文件中,然后在你的 Android 项目中引入该文件。
在你的 Activity 或 Fragment 中,你可以通过以下方法来使用上述代码:
```java
private AudioRecorder audioRecorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audioRecorder = new AudioRecorder();
}
public void startRecording(View view) {
audioRecorder.startRecording();
}
public void stopRecording(View view) {
audioRecorder.stopRecording();
}
```
这里我们假设你在布局文件中创建了两个按钮,分别用于启动和停止录制。在 `startRecording()` 方法中,我们创建了一个新的线程来执行音频数据写入文件的操作。在 `stopRecording()` 方法中,我们停止录制并释放相关资源。
请注意,上述代码中的文件路径是 `/sdcard/recording.wav`。如果你的设备没有 SD 卡或者你的应用程序没有 SD 卡写入权限,那么你需要修改文件路径。
阅读全文