gpt4 book ai didi

android - 在android中使用MIC以mp3格式录制音频

转载 作者:行者123 更新时间:2023-11-30 02:52:29 25 4
gpt4 key购买 nike

我想在 android 中使用 MIC 以 mp3 格式录制音频。我尝试记录下面的代码,但是当我检查 sdcard(路径:sdcard/recording.mp3)时,该文件不起作用。(文件大小为 0kb)。

如何在 android 中以 mp3 或 wav 格式录制麦克风音频。请帮忙。

private final int FREQUENCY = 11025;
private final int CUSTOM_FREQ_SOAP = 1;
private final int OUT_FREQUENCY = FREQUENCY * CUSTOM_FREQ_SOAP;
private final int CHANNEL_CONTIGURATION = AudioFormat.CHANNEL_CONFIGURATION_MONO;
private final int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;

======

try {
mRecordingFile = File.createTempFile("recording", ".mp3", new File("/sdcard/"));


} catch (IOException e) {
throw new RuntimeException("Couldn't create file on SD card", e);
}

======

private class RecordAudio extends AsyncTask<Void, Integer, Void> {
@Override
protected Void doInBackground(Void... params) {
isRecording = true;
try {
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(new FileOutputStream(
mRecordingFile, true)));

int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
CHANNEL_CONTIGURATION, AUDIO_ENCODING);

AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, FREQUENCY,
CHANNEL_CONTIGURATION, AUDIO_ENCODING, bufferSize);

short[] buffer = new short[bufferSize];
audioRecord.startRecording();

while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0,
bufferSize);
int amplitude = 0;
for (int i = 0; i < bufferReadResult; i++) {
dos.writeShort(buffer[i]);
amplitude += Math.abs((int) buffer[i]);
}
final int amp = amplitude;

}

audioRecord.stop();
//dos.close();


} catch (Throwable t) {
}

return null;
}

最佳答案

public void recordAudio(String fileName) {
final MediaRecorder recorder = new MediaRecorder();
ContentValues values = new ContentValues(3);
values.put(MediaStore.MediaColumns.TITLE, fileName);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile("/sdcard/sound/" + fileName);
try {
recorder.prepare();
} catch (Exception e){
e.printStackTrace();
}

final ProgressDialog mProgressDialog = new ProgressDialog(MyActivity.this);
mProgressDialog.setTitle(R.string.lbl_recording);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setButton("Stop recording", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mProgressDialog.dismiss();
recorder.stop();
recorder.release();
}
});

mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface p1) {
recorder.stop();
recorder.release();
}
});
recorder.start();
mProgressDialog.show();
}

关于android - 在android中使用MIC以mp3格式录制音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23904834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com