在Android上使用麦克风,您可以使用Android的AudioRecord类。以下是一个简单的示例代码:
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final int SAMPLE_RATE = 44100;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
private AudioRecord audioRecord;
private Button startButton;
private Button stopButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = findViewById(R.id.start_button);
stopButton = findViewById(R.id.stop_button);
startButton.setOnClickListener(v -> startRecording());
stopButton.setOnClickListener(v -> stopRecording());
audioRecord = new AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.MIC)
.setAudioFormat(new AudioFormat.Builder()
.setEncoding(AUDIO_FORMAT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(CHANNEL_CONFIG)
.build())
.setBufferSizeInBytes(BUFFER_SIZE)
.build();
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Toast.makeText(this, "AudioRecord initialization failed", Toast.LENGTH_SHORT).show();
finish();
}
}
private void startRecording() {
audioRecord.startRecording();
Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show();
new Thread(() -> {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/record.pcm");
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
bytesRead = audioRecord.read(buffer, 0, BUFFER_SIZE);
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
private void stopRecording() {
audioRecord.stop();
Toast.makeText(this, "Recording stopped", Toast.LENGTH_SHORT).show();
}
}
这个示例代码将使用Android的AudioRecord类来捕获麦克风输入,并将其保存到一个PCM文件中。您可以根据需要修改这个示例代码,以满足您的需求。
领取专属 10元无门槛券
手把手带您无忧上云